SwiftUI

.focused()的用法

2021-09-21  本文已影响0人  王勋才


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("聚焦")
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读