当我使用键盘将文本输入到 TextField 时如何阻止分隔线消失

时间:2021-04-10 20:11:37

标签: swiftui

我正在处理登录视图,我有两个 Dividers(),一个在用户名文本字段下划线,另一个在密码文本字段下划线。使用物理设备进行模拟,当我尝试在用户名字段中输入文本时,它的文本字段下方的分隔符消失,然后在我关闭键盘时重新出现,但是密码分隔符不会发生这种情况。

此外,如果我删除位于 TextField 顶部的图像视图,则不会发生此行为。关于为什么会发生这种情况以及如何解决此问题的任何建议?

非常感谢!

VStack{

    Image(uiImage: #imageLiteral(resourceName: "awText"))
        .resizable()
        .frame(width: 180, height: 100)
        .padding(.bottom, 50)
    
    TextField("Username", text: $username)
        .padding(.leading)
    Divider()
        .padding(.bottom)
        .onChange(of: self.username, perform: { value in
            if value.count > 10 {
                self.username = String(value.prefix(10)) //Max 10 Characters for Username.
            }
        })
        .disableAutocorrection(true)
    
    SecureField("Password", text: $password)
        .padding(.leading)
    Divider()
        .onChange(of: self.username, perform: { value in
            if value.count > 10 {
                self.username = String(value.prefix(10)) //Max 10 Characters for Password.
            }
        })
        .disableAutocorrection(true)

}

1 个答案:

答案 0 :(得分:1)

用矩形试试这个代码!


struct ContentView: View {
    
    @State private var username: String = String()
    @State private var password: String = String()

    var body: some View {
        
        VStack{
            Image(systemName: "star")
                .resizable()
                .frame(width: 180, height: 100)
                .padding(.bottom, 50)
            
            TextField("Username", text: $username)
                .padding(.leading)
            
            Rectangle().fill(Color.gray.opacity(0.25)).frame(height: 1, alignment: .center).padding(.bottom)
                
   
            SecureField("Password", text: $password)
                .padding(.leading)
            
            Rectangle().fill(Color.gray.opacity(0.25)).frame(height: 1, alignment: .center)

        }
        .disableAutocorrection(true)
        .onChange(of: self.username, perform: { value in
            if value.count > 10 {
                self.username = String(value.prefix(10))
            }
        })
        .onChange(of: self.username, perform: { value in
            if value.count > 10 {
                self.username = String(value.prefix(10))
            }
        })
        
        
    }

}