self.isLinkActive = true will not load the model view - swiftui

Why can SwiftUI not just load the view it shouldn't b e this hard to do something that could be done in UIKit in one stupid line. the button should simply load what its told to load in this case VideoList(viewModel: .init()) there should be no problem.
import Foundation
import SwiftUI
struct SwiftUIView: View {
#State private var isLinkActive = false
let layout = [
GridItem(.adaptive(minimum: 150))
]
var body: some View {
///Top Bar layout
ZStack {
HStack {
Button(action: {
}, label: {
Image("Home")
.resizable()
.frame(width: CGFloat(30), height: CGFloat(30), alignment: .leading)
}).padding(.leading, CGFloat(20))
.padding(.top, 15)
Spacer()
}
HStack {
Text("app")
.frame(alignment: .center)
.font(.title3)
.foregroundColor(Color("Menu"))
.multilineTextAlignment(.center)
.padding(.top, 15)
}
}
///Setup app FEED LINE
HStack{
Text("app FEED")
.padding(.leading, 20.0)
.padding(.top, 100.0)
.font(.largeTitle)
.foregroundColor(Color("Menu"))
Spacer()
}
///Setup Welcom messages
HStack{
Text("Good morning")
.padding(.bottom, 20)
.padding(.leading, 20.0)
.font(.subheadline)
.foregroundColor(Color("Menu"))
Spacer()
Text("...")
.foregroundColor(/*#START_MENU_TOKEN#*/.blue/*#END_MENU_TOKEN#*/)
.font(.largeTitle)
.padding(.trailing, 20.0)
.padding(.bottom, 20)
}
/// Setup navigation home
ScrollView {
LazyVGrid(columns: layout, spacing: 5) {
Button(action: {
print("Button action")
}) {
Image("app")
}
.padding(.vertical, 2.5)
.padding(.horizontal, 2.5)
Button(action: {
print("Button action")
}) {
Image("app")
}
.padding(.vertical, 2.5)
.padding(.horizontal, 2.5)
Button(action: {
self.isLinkActive = true
}) {
Image("app")
}
.padding(.vertical, 2.5)
.padding(.horizontal, 2.5)
Button(action: {
print("Button action")
}) {
Image("app")
}
Button(action: {
print("Button action")
}) {
Image("app")
}
.padding(.vertical, 2.5)
.padding(.horizontal, 2.5)
Button(action: {
print("Button action")
}) {
Image("app")
}
//Add correct images Direction and Contact us
Button(action: {
print("Button action")
}) {
Image("app")
}
Button(action: {
print("Button action")
}) {
Image("app")
}
.padding(.vertical, 2.5)
.padding(.horizontal, 2.5)
}
}
.padding(.horizontal, 2.5)
.padding(.vertical, 2.5)
.navigationBarTitle("", displayMode: .inline)
.navigationBarHidden(true)
.background(
NavigationLink(destination: VideoList(viewModel: .init()), isActive: $isLinkActive) {
EmptyView()
}
.hidden()
)
}
}
struct VideoList: View {
#Environment(\.presentationMode) private var presentationMode
#ObservedObject private(set) var viewModel: ViewModel
#State private var isRefreshing = false
var body: some View {
NavigationView {
List(viewModel.videos.sorted { $0.id > $1.id}, id: \.id) { video in
NavigationLink(
destination: VideoDetails(viewModel: VideoDetails.ViewModel(video: video))) {
VideoRow(video: video)
}
}
.onPullToRefresh(isRefreshing: $isRefreshing, perform: {
self.viewModel.fetchVideos()
})
.onReceive(viewModel.$videos, perform: { _ in
self.isRefreshing = false
})
.navigationBarTitle(viewModel.navigationBarTitle)
}
.onAppear(perform: viewModel.fetchVideos)
}
}
#if DEBUG
struct VideoList_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
VideoList(viewModel: .init())
}
}
}
#endif
The button on line 109 does not load the VideoList(viewModel: .init()) ViewModel when requested to do so.

NavigationView {} was forgotten however the UI is still messed up currently
and adding an HStack fixed.... ugh hope this helps the next guy not have to spend 3 days on it

Related

hiding the navigation bar while scrolling SwiftUI

Hello I am new to swiftUI and am making my first app, my current issue is that I am not sure if it is possible to hide my navigation bar while scrolling using the methods I got from a nav bar tutorial I found. I have tried to implement the UINavigationBar stuff but I don't think its at all compatable with what I have so far. I'm pretty sure if I wanted to go that route I would have to rewrite most of what I have to fit that format.
I was hoping that maybe I am missing a step when doing this so I don't have to rewrite what I have
here's my current code
import Foundation
import SwiftUI
struct ContentView: View{
#State var showMenu = false
#State var scoreUp = false
#State var commentP = false
#State var tags = false
#State var sauce = false
var body: some View{
let drag = DragGesture()
.onEnded {
if $0.translation.width < -100 {
withAnimation {
self.showMenu = false
}
}
}
let dragOpen = DragGesture()
.onEnded {
if $0.translation.width > 100 {
withAnimation {
self.showMenu = true
}
}
}
return NavigationView {
GeometryReader { geometry in
ZStack(alignment: .leading) {
/// this is the main view for the second page allowing most of the app features
MainView(showMenu: self.$showMenu, scoreUp: self.$scoreUp, commentP : self.$commentP,tags : self.$tags,sauce :self.$sauce)
.frame(width: geometry.size.width, height: geometry.size.height)
.offset(x: self.showMenu ? geometry.size.width/2 : 0)
.disabled(self.showMenu ? true : false)
.gesture(dragOpen)
if self.showMenu {
HamburgerMenuView(showMenu: self.$showMenu)
.frame(width: geometry.size.width/2, height: geometry.size.height)
.transition(.move(edge: .leading))
.gesture(drag)
}
if self.scoreUp {
// TO DO : MAke this button score up a post
Image(systemName: "arrow.up")
.animation(.interpolatingSpring(stiffness: 50, damping: 1), value: 10)
}
}
}
.navigationBarItems(leading: (
Button(action: {
withAnimation {
self.showMenu.toggle()
}
}) {
Image(systemName: "line.horizontal.3")
.imageScale(.large)
}
))
}
}
}
// this is the main view for both the content view and when the menu is displayed
struct MainView: View{
/// shows the hamburger menu when set to true
#Binding var showMenu : Bool
/// SCORES up posts when set to true
#Binding var scoreUp : Bool
/// allows the user to add a comment to the post if set to true
/// move the view up and give the user a text box
#Binding var commentP : Bool
/// allows the user to see the Tags on the image
#Binding var tags : Bool
/// allows the user to see the Source on the image
#Binding var sauce : Bool
var body: some View {
GeometryReader { geometry in
ZStack() {
Image("");
ScrollView {
VStack(spacing: 20) {
VStack(alignment: HorizontalAlignment.leading){
Text("Test")
.bold();
Image("Test")
.resizable()
.scaledToFit()
HStack() {
Button(action : {
withAnimation{
self.scoreUp = true
}
print("Score up")
}) {
Image(systemName: "arrow.up")
.padding(1)
};
Text("1025");
Button(action : {
withAnimation{
self.commentP = true
}
print("comment")
}) {
Image(systemName: "text.bubble")
.padding(1)
};
Button(action : {
withAnimation{
self.tags = true
}
print("Tags")
}) {
Image(systemName: "tag")
.padding(1)
};
Button(action : {
withAnimation{
self.sauce = true
}
print("sauce?")
}) {
Image(systemName: "eyes")
.padding(1)
};
}
Text("Test")
Image("Test")
.resizable()
.scaledToFit();
Text("Test")
Image("Test")
.resizable()
.scaledToFit()
}
Button(action: {
withAnimation {
self.showMenu = true
}
print("Open the side menu")
}) {
Text("Show Menu");
}
.hidden()
}
}
}
}
}
}
/// this is the hamburger menu itself
struct HamburgerMenuView : View {
#Binding var showMenu : Bool
var body: some View {
GeometryReader { geometry in
VStack(alignment: .leading) {
HStack {
Image(systemName: "person")
.foregroundColor(.gray)
.imageScale(.large)
Text("Profile")
.foregroundColor(.gray)
.font(.headline)
.padding(10)
}
HStack {
Image(systemName: "gear")
.foregroundColor(.gray)
.imageScale(.large)
Text("Settings")
.foregroundColor(.gray)
.font(.headline)
.padding(10)
}
HStack {
Image(systemName: "person")
.foregroundColor(.gray)
.imageScale(.large)
Text("Favorites")
.foregroundColor(.gray)
.font(.headline)
.padding(10)
}
HStack {
Image(systemName: "person")
.foregroundColor(.gray)
.imageScale(.large)
Text("Posts")
.foregroundColor(.gray)
.font(.headline)
.padding(10)
}
HStack {
Image(systemName: "person")
.foregroundColor(.gray)
.imageScale(.large)
Text("Comments")
.foregroundColor(.gray)
.font(.headline)
.padding(10)
}
HStack {
Image(systemName: "person")
.foregroundColor(.gray)
.imageScale(.large)
Text("Artists")
.foregroundColor(.gray)
.font(.headline)
.padding(10)
}
HStack {
Image(systemName: "person")
.foregroundColor(.gray)
.imageScale(.large)
Text("Tags")
.foregroundColor(.gray)
.font(.headline)
.padding(10)
}
HStack {
Image(systemName: "person")
.foregroundColor(.gray)
.imageScale(.large)
Text("More")
.foregroundColor(.gray)
.font(.headline)
.padding(10)
}
}
.padding()
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
.background(Color(red: 32/255, green: 32/255, blue: 32/255))
.edgesIgnoringSafeArea(.all)
}
Spacer()
}
}
//// TO DO
//class underImageBar {
//
//
//HStack() {
//Button(action : {
// withAnimation{
// self.scoreUp = true
//}
// print("Score up")
// }) {
// Image(systemName: "arrow.up")
// .padding()
//
//
// };
//Button(action : {
// withAnimation{
// self.commentP = true
//}
// print("comment")
// }) {
// Image(systemName: "text.bubble")
// .padding()
//
//
// };
//Button(action : {
// withAnimation{
// self.tags = true
//}
// print("Tags")
// }) {
// Image(systemName: "tag")
// .padding()
// };
//Button(action : {
// withAnimation{
// self.sauce = true
// }
// print("sauce?")
// }) {
// Image(systemName: "eyes")
// .padding()
//
// };
// }
//}
/// this previews the code
struct menuView: PreviewProvider {
static var previews: some View {
Group {
ContentView()
.toolbar {
}
}
}
}
this was supposed to be a gif stack overflow just made it a jpeg lol?
There is a view modifier for that.
.navigationBarHidden(true)
I hope this helps out.

How Can I Handle Tap Gesture on Widget?

I'm writing a widget with WidgetKit and I want to make the widget's content is clickable. For example, if users click to standings, I want to open the standings tab when the app becomes active.
I tried to use notification between the app and widget but the tap gesture is not working, I added print inside of the tap gesture but it did not appear in the console. Also, I added the same app group to both of them.
WidgetView:
struct LargeWidget : View {
#State var standings : [StandingsTable]
var body: some View {
VStack(alignment:.leading){
if standings.count > 0{
HStack(spacing:5){
Text("#").foregroundColor(.gray)
.frame(width: 30)
Text("Team".localized).foregroundColor(.gray)
Spacer()
Text("_D".localized).foregroundColor(.gray)
.frame(width: 30)
Text("_L".localized).foregroundColor(.gray)
.frame(width: 30)
Text("_W".localized).foregroundColor(.gray)
.frame(width: 30)
Text("_P".localized).foregroundColor(.gray)
.frame(width: 30)
}
Divider()
ForEach(0..<5, id: \.self) { i in
HStack(spacing:5){
Text(standings[i].rank)
.font(.system(size: 15))
.padding(.vertical, 3)
.frame(width: 30)
.background(Color(UIColor.systemBackground))
.cornerRadius(4)
Text(standings[i].name)
.lineLimit(1)
.padding(.leading, 5)
Spacer()
Text(standings[i].drawn)
.frame(width: 30)
Text(standings[i].lost)
.frame(width: 30)
Text(standings[i].won)
.frame(width: 30)
Text(standings[i].points)
.frame(width: 30)
}
.padding(.vertical, 5)
.background(standings[i].name == "Besiktas" ? Color(UIColor.systemGray6) : Color.clear)
.cornerRadius(8)
}
Spacer(minLength: 0)
}else{
Text("Large")
.padding()
}
}.padding()
.onTapGesture {
print("clicked to standings")
DispatchQueue.main.async(execute: {
NotificationCenter.default.post(name: NSNotification.Name("standings"), object: nil, userInfo: nil)
})
}
}
}
and here ContentView in app:
import SwiftUI
extension NSNotification {
static let openStandings = NSNotification.Name.init("standings")
}
struct ContentView: View {
#State var show: Bool = false
var body: some View {
NavigationView{
Text("Hello, world!")
.padding()
}.sheet(isPresented: self.$show) {
VStack{
Text("Notification")
.padding()
}
}
.onReceive(NotificationCenter.default.publisher(for: NSNotification.openStandings))
{ obj in
self.show.toggle()
}
}
}
Screenshot of Widget
Okay I created a new project with SwiftUI Environments (not old way AppDelegate and SceneDelegate).
Then I use Link for tap actions and I got it with .onOpenURL modifier in ContentView. It works :)
ContentView:
import SwiftUI
enum SelectedTab: Hashable {
case home
case standings
case options
}
struct ContentView: View {
#State var selectedTab: SelectedTab = .home
var body: some View {
TabView(selection: self.$selectedTab) {
Text("Home")
.tabItem {
Image(systemName: "house")
.renderingMode(.template)
Text("Home")
}.tag(SelectedTab.home)
Text("Standings")
.tabItem {
Image(systemName: "list.number")
.renderingMode(.template)
Text("Standings")
}.tag(SelectedTab.standings)
Text("Options")
.tabItem {
Image(systemName: "gear")
.renderingMode(.template)
Text("Options")
}.tag(SelectedTab.options)
.onOpenURL { (url) in
if url.absoluteString == "widget-deeplink://standings"{
self.selectedTab = .standings
}
}
}
}
}
Link usage example in Widget:
Link(destination: URL(string: "widget-deeplink://standings")!) {
Text("Link Test")
}

Tap gesture on buttons response randomly in SwiftUI

I have a My Profile form in my app. In the form I have some buttons. Among them 5 buttons are used to present custom drop down menus to select Sax, Blood, Nationality, and so on. However, when I tap these buttons sometime they response some time don't. For example, if I tap them 10 time they response 2 or 3 times. Some time they work for long tap. I have spent days on this matter, but could not identify any problem in my code. Is there anyone who faced this sort of problems? Could anyone figure out what is the actual problem. By the way, all other buttons in my app working absolutely fine.
This is the code for first 3 buttons in red rectangle in the picture
import SwiftUI
struct FormPartTwoView: View {
#Binding var gender: String
#Binding var blood: String
#Binding var nationality: String
#Binding var showingGenderPicker: Bool
#Binding var showingBloodGroupPicker: Bool
#Binding var showingNationalityPicker: Bool
#ObservedObject var userProfile = UserProfileViewModel()
#ObservedObject var userProfileUpdate = UserProfileUpdateViewModel()
var body: some View {
GeometryReader { geometry in
HStack {
Button(action: {
self.showingGenderPicker.toggle()
self.showingBloodGroupPicker = false
self.showingNationalityPicker = false
}) {
VStack {
TextField("Gender", text: self.$gender)
.padding(.horizontal)
.disabled(true)
}
.font(.system(size: 13))
.frame(height: 40)
.overlay(
RoundedRectangle(cornerRadius: 5)
.stroke(Color("Border2"), lineWidth: 1)
)
}
.buttonStyle(PlainButtonStyle())
Button(action: {
self.showingBloodGroupPicker.toggle()
self.showingGenderPicker = false
self.showingNationalityPicker = false
}) {
VStack {
TextField("Blood", text: self.$blood)
.padding(.horizontal)
.disabled(true)
}
.font(.system(size: 13))
.frame(height: 40)
.overlay(
RoundedRectangle(cornerRadius: 5)
.stroke(Color("Border2"), lineWidth: 1)
)
}
.buttonStyle(PlainButtonStyle())
Button(action: {
self.showingNationalityPicker.toggle()
self.showingGenderPicker = false
self.showingBloodGroupPicker = false
}) {
VStack {
TextField("Nationality", text: self.$nationality)
.padding(.horizontal)
.disabled(true)
}
.font(.system(size: 13))
.frame(height: 40)
.overlay(
RoundedRectangle(cornerRadius: 5)
.stroke(Color("Border2"), lineWidth: 1)
)
}
.buttonStyle(PlainButtonStyle())
}
.frame(width: geometry.size.width, height: 40)
}
}
}
struct FormPartTwoView_Previews: PreviewProvider {
static var previews: some View {
FormPartTwoView(gender: .constant(""), blood: .constant(""), nationality: .constant(""), showingGenderPicker: .constant(false), showingBloodGroupPicker: .constant(false), showingNationalityPicker: .constant(false))
}
}
This is the code for second tow Buttons:
import SwiftUI
struct FormPartFiveView: View {
#Binding var district: String
#Binding var upazila: String
#Binding var postcode: String
#Binding var showingUpazilaPicker: Bool
#Binding var showingDistrictPicker: Bool
#ObservedObject var userProfileUpdate = UserProfileUpdateViewModel()
var body: some View {
GeometryReader { geometry in
HStack {
Button(action: {
self.showingDistrictPicker.toggle()
self.showingUpazilaPicker = false
}) {
VStack {
Text("\(self.district == "" ? "District" : self.district)")
.foregroundColor(self.district == "" ? Color.gray : Color.black)
.padding(.horizontal)
}
.font(.system(size: 13))
.frame(width: geometry.size.width/3.2, height: 40)
.overlay(
RoundedRectangle(cornerRadius: 5)
.stroke(Color("Border2"), lineWidth: 1)
)
}
.buttonStyle(PlainButtonStyle())
Button(action: {
self.showingUpazilaPicker.toggle()
self.showingDistrictPicker = false
}) {
VStack {
Text("\(self.upazila == "" ? "Upazila" : self.upazila)")
.foregroundColor(self.upazila == "" ? Color.gray : Color.black)
.padding(.horizontal)
}
.font(.system(size: 13))
.frame(width: geometry.size.width/3.2, height: 40)
.overlay(
RoundedRectangle(cornerRadius: 5)
.stroke(Color("Border2"), lineWidth: 1)
)
}
.buttonStyle(PlainButtonStyle())
VStack {
TextField("Postcode", text: self.$postcode)
.padding(.horizontal)
}
.font(.system(size: 13))
.frame(width: 100, height: 40)
.overlay(
RoundedRectangle(cornerRadius: 5)
.stroke(Color("Border2"), lineWidth: 1)
)
}
.frame(width: geometry.size.width, height: 40)
}
}
}
struct FormPartFiveView_Previews: PreviewProvider {
static var previews: some View {
FormPartFiveView(district: .constant(""), upazila: .constant(""), postcode: .constant(""), showingUpazilaPicker: .constant(false), showingDistrictPicker: .constant(false))
}
}

Horizontal scrollview is not working swiftUI

i'm trying to show some horizontal view but it's not working. below are the code i'm using.
#State var userDataList = [UserModel]()
var body: some View{
VStack(spacing: 10){
VStack{
prefView()
.padding(.bottom, 30)
Text("Tap to start making friend")
}
ScrollView(.horizontal, content: {
HStack(spacing: 10) {
ForEach(userDataList) { user in
NavigationLink(destination: ChatView(chatMember: self.chatmember, user: user)){
SearchUser()
}
}
}
.padding(.leading, 10)
})
.frame(width: 300, height: 400)
Spacer()
}
.navigationBarTitle("Profile",displayMode: .inline)
.onAppear {
self.userList()
}
}
But if i change the above code with below than it work i don't know how please help me.
ScrollView(.horizontal, content: {
HStack(spacing: 10) {
ForEach(0..< 2) { index in
NavigationLink(destination: ChatView(chatMember: self.chatmember, user: user)){
SearchUser()
}
}
}
.padding(.leading, 10)
})
Thanks in advance

SwiftUI ActionSheet Picker

I'm trying to create in SwiftUI an action sheet that appears after pressing a button and allow the user to select and return an item throught a picker (like this https://imgur.com/a/IbS7swX).
Any hint on how to do it?
Thanks
struct ContentView: View {
init() {
UITableView.appearance().separatorColor = .clear
}
var inputArray = ["100","101","102"]
#State var slectedSegmant = "ActionSheet"
#State var slectedObj = "101"
#State var enableSheet = false
var test = false
var body: some View {
ZStack {
VStack(spacing: 10) {
Picker(selection: $slectedSegmant, label: Text("Segment")) {
Text("Alert").tag("Alert")
Text("ActionSheet").tag("ActionSheet")
}.pickerStyle(SegmentedPickerStyle())
.labelsHidden()
.padding(EdgeInsets.init(top: 50, leading: 10, bottom: 0, trailing: 10))
Text("Alert & Pickers")
.font(Font.system(size: 35, design: .rounded))
.fontWeight(.bold)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal)
List((0...50),id: \.self) { input in
ZStack {
HStack(spacing: 10) {
Image(systemName: "book")
.font(.title)
.padding(.leading, 10)
VStack(alignment: .leading, spacing: 5, content: {
Text("Simple")
Text("3 different buttons")
})
Spacer()
}.padding(.vertical)
.frame(maxWidth:.infinity)
.background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.white).shadow(radius: 1.5)
)
Button(action: {
self.enableSheet = true
}) {
Text("")
}
}
}.padding()
}.blur(radius: $enableSheet.wrappedValue ? 1 : 0)
.overlay(
$enableSheet.wrappedValue ? Color.black.opacity(0.6) : nil
)
if $enableSheet.wrappedValue {
GeometryReader { gr in
VStack {
VStack {
Text("PickerView")
.font(.headline)
.foregroundColor(.gray)
.padding(.top, 10)
Text("Prefered ContentHeight")
.padding(.top, 5)
Picker("test", selection: self.$slectedObj) {
Text("100").id("100")
Text("101").id("101")
Text("101").id("102")
}.labelsHidden()
}.background(RoundedRectangle(cornerRadius: 10)
.foregroundColor(Color.white).shadow(radius: 1))
VStack {
Button(action: {
debugPrint("Done Selected")
self.enableSheet = false
}) {
Text("Done").fontWeight(Font.Weight.bold)
}.padding()
.frame(maxWidth: gr.size.width - 90)
.background(RoundedRectangle(cornerRadius: 10)
.foregroundColor(Color.white).shadow(radius: 1))
}
}.position(x: gr.size.width / 2 ,y: gr.size.height - 200)
}
}
}.edgesIgnoringSafeArea(.all)
}
}
OUTPUT