在 SecureField 的 SwiftUI 中切换 isSecureTextEntry

2024-04-27

我想实现在 SecureField 中显示和隐藏密码的功能。 以下是 SecureField 的代码 我添加了按钮,该按钮将被检测到显示和隐藏 SecureField 中的文本。 但 swiftUI 没有类似的功能是安全文本条目除了切换之外还有其他方法吗文本域 and 安全现场 here https://stackoverflow.com/questions/63095851/show-hide-password-how-can-i-add-this-feature

SecureField(placeholder, text: $textValue, onCommit: {
    onReturn?()
})
.onTapGesture {
    onBegin?()
}
.keyboardType(keyboardType)
.font(Font.label.bodyDefault)
.disableAutocorrection(true)
.frame(maxWidth: .infinity, maxHeight: 40)
.padding(.leading)

这并不像应有的那么简单。其中一个答案非常接近,但它并不能完全涵盖所有内容,因为它的实现很差@FocusState。 iOS 15 确实让这个字段更容易构建,因为有两个关键: 1. 使用.opacity()显示和隐藏字段,2.使用@FocusState以便在两个领域之间实现无缝过渡。此方法的唯一缺点是为了实现无缝转换,您必须将键盘限制为仅兼容 ASCII 的字符,因此某些语言被排除在外,例如俄语。

struct CustomSecureField: View {
    
    @FocusState var focused: focusedField?
    @State var showPassword: Bool = false
    @Binding var password: String
    
    var body: some View {
        HStack {
            ZStack(alignment: .trailing) {
                TextField("Password", text: $password)
                    .focused($focused, equals: .unSecure)
                    .autocapitalization(.none)
                    .disableAutocorrection(true)
                // This is needed to remove suggestion bar, otherwise swapping between
                // fields will change keyboard height and be distracting to user.
                    .keyboardType(.alphabet)
                    .opacity(showPassword ? 1 : 0)
                SecureField("Password", text: $password)
                    .focused($focused, equals: .secure)
                    .autocapitalization(.none)
                    .disableAutocorrection(true)
                    .opacity(showPassword ? 0 : 1)
                Button(action: {
                    showPassword.toggle()
                    focused = focused == .secure ? .unSecure : .secure
                }, label: {
                    Image(systemName: self.showPassword ? "eye.slash.fill" : "eye.fill")
                        .padding()
                })
            }
        }
    }
    // Using the enum makes the code clear as to what field is focused.
    enum focusedField {
        case secure, unSecure
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 SecureField 的 SwiftUI 中切换 isSecureTextEntry 的相关文章

随机推荐