Updated for Xcode 12.0
New in iOS 14
SwiftUI lets us attach an onChange()
modifier to any view, which will run code of our choosing when some state changes in our program. This is important, because we can’t use property observers like didSet
with something like @State
.
For example, this will print name changes as they are typed:
struct ContentView : View {
@State private var name = ""
var body: some View {
TextField("Enter your name:", text: $name)
.textFieldStyle(RoundedBorderTextFieldStyle())
.onChange(of: name) { newValue in
print("Name changed to \(name)!")
}
}
}
SPONSORED From January 26th to 31st you can join a FREE crash course for iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a senior developer!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.