I’m fairly new to Swift and SwiftUI but the following code seems pretty straightforward. I’ve stripped it down to a really simple example.
I’m trying to use .disabled to enable/disable a button based on the contents of a text field. I’ve got two examples in the code snippet - the first uses a String variable and works fine. As soon as I type something, the button enables. The second example is identical except that it uses a String inside a Class. Doesn’t matter what I type, button never enables.
I’ve tried it with and without the ObservableObject and @Published declarations.
Using Xcode 11.2.
Any thoughts would be welcome
class User: ObservableObject {
@Published var name: String
init() {
name = ""
}
}
struct ContentView: View {
@State var user = User()
@State var username = “”
var body: some View {
VStack {
TextField("New Name", text: $username)
Button(action: {print(self.username)}) {Text("String")}.disabled(self.username.count <= 2)
TextField("New Name", text: $user.name)
Button(action: {print(self.user.name)}) {Text("User Class")}.disabled(self.user.name.count <= 2)
}
}
}