Hey!
Is there any opportunity in SwiftUI to keep a global variable that can changed its value and not cause views refresh (because I'm not going to display the value of this var)?
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Created
Hi!
I'm learning SwiftUI and now got stuck with a problem of using @EnvironmentObject. The problem is: I get an email inputed by user and I have to pass it through several view (each view I call with NavigationLink). But I get an error sometimes:
struct RepeatPinView: View {
@State var pin: String
@State var pinRepeat: String = ""
@State var text: String = "Repeat PIN"
@State var selection: String? = nil
@EnvironmentObject var globalObj: GlobalObj
@Environment(\.colorScheme) var colorScheme
var body: some View {
let buttons: [[numPadButton]] = [
[.one, .two, .three],
[.four, .five, .six],
[.seven, .eight, .nine],
[.dop, .zero, .del],
]
VStack {
NavigationLink(destination: ContentView(), tag: "GotPin", selection: $selection) { EmptyView() }
Spacer()
// Text("Pin repeat \(globalObj.email)")
/* here I'm trying to check the email but sometimes and sometimes not (whaat.. can't understand how it works) I get a Fatal error: No ObservableObject of type GlobalObj found
*/
Text(text)
.font(.system(size: 30))
Spacer()
Text(pinRepeat)
.font(.system(size: 30))
.onChange(of: pinRepeat) { pinRepeat in
print(pinRepeat)
// print(globalObj.email)
/* same problem, sometimes get a Fatal error*/
if pinRepeat.count == 4 {
if self.pinRepeat == pin {
print(globalObj.email)
let textToWrite = globalObj.email + "\n" + pinRepeat
print(textToWrite)
/* surprisingly, but here everything works fine WHY??? */
selection = "GotPin"
} else {
text = "Try again"
}
}
}
.frame(width: 100, height: 50, alignment: .center)
Spacer()
ForEach(buttons, id: \.self) { row in
HStack {
ForEach(row, id: \.self) { item in
Button(action: {
switch item.rawValue {
case "dop":
print("dop")
case "del":
print("del")
if pinRepeat != "" {
pinRepeat.removeLast()
}
default:
pinRepeat.append(item.rawValue)
}
}, label: {
if item.rawValue == "del" {
Image(systemName: "delete.left")
.font(.title)
.foregroundColor(colorScheme == .dark ? .white : .black)
.padding()
} else if item.rawValue == "dop" {
Text("")
.font(.title)
.foregroundColor(colorScheme == .dark ? .white : .black)
.padding()
} else {
Text(item.rawValue)
.fontWeight(.bold)
.font(.largeTitle)
.foregroundColor(colorScheme == .dark ? .white : .black)
.padding()
.background(
Circle()
.stroke(Color.yellow, lineWidth: 4)
.frame(width: buttonWidth(item: item) - 5, height: buttonHeight(item: item) - 5, alignment: .center)
)
}
})
.frame(width: buttonWidth(item: item), height: buttonHeight(item: item), alignment: .center)
.padding([.trailing, .leading], 7)
}
}
.padding(.bottom, 7)
}
Spacer()
Spacer()
Spacer()
}
}
}
In previous views (there are three views before this one) I never got a Fatal error doing the same things.
Help me, please