xcode SwiftUI FocusState在SwiftUI中不起作用,键盘未切换

pgccezyw  于 2023-06-07  发布在  Swift
关注(0)|答案(1)|浏览(163)

这是我的代码。它不工作,键盘不按预期切换。

import SwiftUI

struct FocusStateBC_: View {
    
    @FocusState private var usernaminFocus : Bool 
    @State private var username : String = ""

    var body: some View {
        VStack {
            TextField("Your name here...", text: $username)
                .focused($usernaminFocus)
                .padding(.leading)
                .frame(height: 50)
                .frame(maxWidth: .infinity)
                .background(Color.gray.brightness(0.3))
            .cornerRadius(10)
            Button("TOOGLE FOCUS STATE"){
                usernaminFocus.toggle()
            }
            
        }.padding(40)
    }
}

struct FocusStateBC__Previews: PreviewProvider {
    static var previews: some View {
        FocusStateBC_()
    }
}

单击文本字段下的按钮后键盘切换

eqfvzcg8

eqfvzcg81#

这是一个preview bug。它适用于模拟器和真实的设备。
如果你真的想让它在预览中也能工作,你可以将预览嵌入到一个像ZStack这样的容器中:

struct FocusStateBC__Previews: PreviewProvider {
    static var previews: some View {
        ZStack { // 👈 Here is the work around
            FocusStateBC_()
        }
    }
}
💡无关但有用的说明:

如果您在Xcode的Edit -> Format -> Spelling And Grammar菜单中打开Check Spelling While Typing,您可以快速识别您在usernaminFocus中拼错了username,然后是错误的cammelCaseing。
应该是usernameInFocus

相关问题