I am new to swift UI and swift in general, and I was wondering how to change a variable from a different struct. In this case, I need to change the logged in boolean in a content view from this section in a different view. Basic explanations would be appreciated. Thanks!
Button(action: {
if (checkKey(testKey: self.key)) {
//HERE
}
}) {
Text("Submit")
.padding()
.background(Color.init(.sRGB, red: 0.01, green: 0.01, blue: 0.01, opacity: 0.05))
.cornerRadius(10)
}
And this is the Content View. I need to change the #State bool
struct ContentView: View {
#State public var loggedin: Bool = false
var body: some View {
NavigationView {
if (loggedin) {
MainView()
} else {
// Not Logged In
LoginScreen()
}
}
}
}
here is a full code you can pass your #State public var loggedin: Bool variable to another struct using #Binding var loggedin: Bool and chnage value
struct ContentView: View {
#State public var loggedin: Bool = false
var body: some View {
NavigationView {
if (loggedin) {
MainView(loggedin: $loggedin)
} else {
// Not Logged In
LoginScreen(loggedin: $loggedin)
}
}
}
}
struct MainView: View {
#Binding var loggedin: Bool
var body: some View {
VStack {
Text("")
Button(action: {
self.loggedin = false
}, label: {
Text("Chnage loggedin value")
})
}
}
}
#Binding var loggedin: Bool
in your login screen view. If you only use the login here its fine like this, if you are using it across the app you might want to look into #EnvironmentObject.
Related
I'm a beginner of SwiftUI. (Sorry in advance if my English is hard to understand.)
I want to enable multiple screen transitions using Modal.
【Go back to the initial view when the view reached to the last View and pressed the button】
That's what I want to realize.
I thought my code would work perfectly but when I pressed the button of last view it stopped at the second view, not the initial view.
Can't figure out what's wrong and where to fix, any solutions?
Here's my code.
`
import SwiftUI
struct ContentView: View {
#State var isShowSecondView = false
var body: some View {
Button("To SecondView") {
isShowSecondView = true
}
.font(.largeTitle)
.fullScreenCover(isPresented: $isShowSecondView) {
SecondView(isShowSecondView: $isShowSecondView)
}
}
}
struct SecondView: View {
#Binding var isShowSecondView: Bool
#State var isShowThirdView = false
var body: some View {
Button("To ThirdView") {
isShowThirdView = true
}
.font(.largeTitle)
.fullScreenCover(isPresented: $isShowThirdView) {
ThirdView(isShowNextView: $isShowSecondView,
isShowThirdView: $isShowThirdView)
}
}
}
struct ThirdView: View {
#Binding var isShowNextView: Bool
#Binding var isShowThirdView: Bool
#State var isShowForthView = false
var body: some View {
Button("To ForthView") {
isShowForthView = true
}
.font(.largeTitle)
.fullScreenCover(isPresented: $isShowForthView) {
ForthView(isShowNextView: $isShowNextView,
isShowThirdView: $isShowThirdView, isShowForthView: $isShowForthView)
}
}
}
struct ForthView: View {
#Binding var isShowNextView: Bool
#Binding var isShowThirdView: Bool
#Binding var isShowForthView: Bool
var body: some View {
Button("Back to FirstView") {
isShowNextView = false
isShowThirdView = false
isShowForthView = false
}
.font(.largeTitle)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
`
Set property wrapper to pop view "#Environment(.presentationMode) var presentationMode" but it is reloading view again and again. Why it is happening? any solution?
What i have observed except #Environment(.presentationMode) we should use bool value binding with controller, Please check code:
struct newView: View {
#State private var isActiveView: Bool = false
var body: some View {
VStack(alignment: .center) {
NavigationLink(destination: PushedView(isActiveView: $isActiveView), isActive: $isActiveView) {
Text("Create Account")
}
}
}
}
And on pushed screen check the code:
`struct PushedView: View {
#Binding var isActiveView: Bool
var body: some View {
NavigationView {
VStack {
Text(“Back”).onTapGesture {
isActiveView = false // to pop into previous view
}
}
}
}
}
`
Building my first SwiftUI app and I'm stuck on pass #State var to the ContentView. I have declared the #State variable in a struct, with an #Binding tag on the variable in the ContentView.
My intent is for multiple instances of NumberBlock to be called in ContentView, and be able to reset all of them to false (hide all of the images) with one button.
The new "App" struct that was added in Xcode 12 is giving an error for a missing parameter. I've tried everything I can think of to enter a parameter, but nothing seems to work. I was able to eliminate the error by using .constant(true), but that did not give me the functionality I need, which is to toggle the variable from the ContentView.
I appreciate any help eliminating the error or correcting my shallow understanding of #State and #Binding.
Here is where I create the #State reset_x var
import SwiftUI
struct NumberBlock: View {
#State var reset_x: Bool = true
#Binding var reset: Bool
var body: some View {
ZStack {
Text("test")
.onTapGesture(count: 1, perform: {
self.reset_x = false
})
Image("XMark")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 50, height: 50, alignment: .center)
.onTapGesture(count: 1, perform: {
self.reset_x = true
print("reset_x is \(self.reset_x)")
})
.isHidden(reset_x ? true : false)
.isHidden(reset ? true : false)
}
}
}
The error occurs in this view:
import SwiftUI
#main
struct Quixx2App: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
Here is where I want to use the #Binding
import SwiftUI
struct ContentView: View {
#State var reset: Bool = false
#Binding var reset_x: Bool
var body: some View {
VStack {
HStack {
NumberBlock(reset: self.$reset)
NumberBlock(reset: self.$reset)
}
Button("Reset Score"){
self.scoreKeeper.redScore = 0
self.reset_x = false //this line is not doing anything
print("reset_x is \(self.reset_x)")
}
}
}
}
And the .isHidden extension
import Foundation
import SwiftUI
extension View {
#ViewBuilder func isHidden(_ hidden: Bool, remove: Bool = false) -> some View {
if hidden {
if !remove {
self.hidden()
}
} else {
self
}
}
}
So let's start with your NumberBlock view. You need one state within the View, which preserves if the image is hidden or not. By tapping the Text View, the the value is toggled and the view is rendered accordingly.
struct NumberBlock: View {
#State private var imageIsHidden: Bool
var body: some View {
VStack {
Text("Show")
.onTapGesture(count: 1, perform: {
self.imageIsHidden = false
})
Text("Image")
.onTapGesture(count: 1, perform: {
self.imageIsHidden = true
})
.isHidden(imageIsHidden ? true : false)
}
}
}
Now, you want a second feature: The ContentView should control this state. So you have to extract this state from the child view (NumberBlock) to the parent view (ContentView). By changing the property from #State to #Binding you are basically telling the child view that this data is being passed from a parent view.
My working example:
import SwiftUI
import Foundation
extension View {
#ViewBuilder func isHidden(_ hidden: Bool, remove: Bool = false) -> some View {
if hidden {
if !remove {
self.hidden()
}
} else {
self
}
}
}
struct NumberBlock: View {
#Binding var imageIsHidden: Bool
var body: some View {
VStack {
Text("Show")
.onTapGesture(count: 1, perform: {
self.imageIsHidden = false
})
Text("Image")
.onTapGesture(count: 1, perform: {
self.imageIsHidden = true
})
.isHidden(imageIsHidden ? true : false)
}
}
}
struct ContentView: View {
#State var imageOfBlock1IsHidden: Bool = true
#State var imageOfBlock2IsHidden: Bool = true
var body: some View {
VStack {
HStack {
NumberBlock(imageIsHidden: self.$imageOfBlock1IsHidden)
NumberBlock(imageIsHidden: self.$imageOfBlock2IsHidden)
}
Button("Reset Score") {
self.imageOfBlock1IsHidden = true
self.imageOfBlock2IsHidden = true
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I currently use an landscape environmentobject based on this code - https://stackoverflow.com/a/58503841/412154
Within my view I have modals that appear and disappear appropriately using #State/#Binding depending on a "Done" Button press. My app does show a different view when rotated to landscape and I would like for the modal to dismiss automatically on the rotation, but couldn't figure out how to change the #binding var based on another #ennvironmentobject
Here is a simplified sample of my Modal View
struct StepsView: View {
#Binding var isPresented:Bool
#EnvironmentObject var orientation:Orientation
var body: some View {
VStack(alignment: .center) {
Text("Step")
}
.navigationBarItems(trailing: Button(action: {
//print("Dismissing steps view...")
self.isPresented = false
}) {
Text("Done").bold()
})
}
thanks for any help!
Appreciate #davidev's answer but I wanted each Modal to act a little differently so I did it this way
struct StepsView: View {
#Binding var isPresented:Bool
#EnvironmentObject var orientation:Orientation
private var PortraitView:some View {
VStack(alignment: .center) {
Text("Modal")
}
.navigationBarItems(trailing: Button(action: {
self.isPresented = false
}) {
Text("Done").bold()
})
}
var body: some View {
buildView(isLandscape: orientation.isLandScape, isShowing: &isPresented)
}
func buildView(isLandscape:Bool, isShowing:inout Bool) -> AnyView {
if !isLandscape {
return AnyView(PortraitView)
} else {
isShowing = false
return AnyView(EmptyView())
}
}
Here is a possible approach with extending the Device class with a variable which keeps track of the opened modal View.
import Combine
final class Orientation: ObservableObject {
#Published var isLandscape: Bool = false {
willSet {
objectWillChange.send()
if (newValue)
{
self.showModal = false
}
}
}
#Published var showModal : Bool = false
}
Whenever landscape changes, and the orientation is landscape, showModal will be set to false.
Here the ContentView..
struct ContentView6: View {
#EnvironmentObject var orientation:Orientation
// 1.
#State private var showModal = false
var body: some View {
Button("Show Modal") {
// 2.
self.orientation.isLandscape.toggle()
// 3.
}.sheet(isPresented: self.$orientation.isLandscape) {
ModalView(isPresented: self.$orientation.isLandscape).environmentObject(self.orientation)
}
}
}
I don't often understand when SwiftUI resets the state of a view (i.e. all that is marked with #State). For example, take a look at this minimum example:
import SwiftUI
struct ContentView: View {
#State private var isView1Active = true
let view1 = View1()
let view2 = View2()
var body: some View {
VStack {
if isView1Active {
view1
} else {
view2
}
Button(action: {
self.isView1Active.toggle()
}, label: {
Text("TAP")
})
}
}
}
struct View1: View {
#State private var text = ""
var body: some View {
TextField("View1: type something...", text: $text)
}
}
struct View2: View {
#State private var text = ""
var body: some View {
TextField("View2: type something...", text: $text)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I'd want the two TextField to keep their content, but if you run this example some weird behaviours occur:
If you run the example on the preview only the View1 TextField content persists:
If you, instead, run the example on the simulator (or on an actual device) neither the first textfield content, nor the second one persist:
So, what's happening here? Is there a way to tell SwiftUI not to reset #State for a view? Thanks.
The issue is that View1 and View2 are being recreated every time isView1Active is changed (because it is using #State which reloads the body of ContentView).
A solution would be to keep the text properties of the TextFields in the ContentView as shown below and use #Binding:
struct ContentView: View {
#State private var isView1Active = true
#State private var view1Text = ""
#State private var view2Text = ""
var body: some View {
VStack {
if isView1Active {
View1(text: $view1Text)
} else {
View2(text: $view2Text)
}
Button(action: {
self.isView1Active.toggle()
}, label: {
Text("TAP")
})
}
}
}
struct View1: View {
#Binding var text: String
var body: some View {
TextField("View1: type something...", text: $text)
}
}
struct View2: View {
#Binding var text: String
var body: some View {
TextField("View2: type something...", text: $text)
}
}
Shown in action:
It view1 and view2 are completely independent and enclosure, like there is no contextmenuor sheet, you may use ZStack and opacity combinations.
var body: some View {
VStack {
ZStack{
if isView1Active {
view1.opacity(1)
view2.opacity(0)
} else {
view1.opacity(0)
view2.opacity(1)
}}
Button(action: {
self.isView1Active.toggle()
}, label: {
Text("TAP")
})
}
}