import SwiftUI
struct ContentView: View {
enum Field:Hashable{
case name
case age
}
@State var text:String = ""
@FocusState var focusedField:Field?
var body: some View{
VStack {
TextField("hi", text: $text, prompt: Text("name"))
.focused($focusedField, equals: .name)
.textFieldStyle(.roundedBorder)
.padding()
TextField("hi", text: $text, prompt: Text("age"))
.focused($focusedField, equals: .age)
.textFieldStyle(.roundedBorder)
.padding()
Button {
focusedField = .name
} label: {
Text("focus name")
}
Button {
focusedField = .age
} label: {
Text("focus age")
}
Button {
focusedField = nil
} label: {
Text("focus nothing")
}
}
}
}
import SwiftUI
struct ContentView: View {
@State var text:String = ""
@FocusState var focusedField:Bool
var body: some View{
VStack {
TextField("hi", text: $text, prompt: Text("name"))
.focused($focusedField)
.textFieldStyle(.roundedBorder)
.padding()
Button {
self.focusedField.toggle()
} label: {
Text("聚焦")
}
}
}
}
网友评论