【问题标题】:toggle isSecureTextEntry in SwiftUI for SecureField在 SwiftUI 中为 SecureField 切换 isSecureTextEntry
【发布时间】:2021-12-27 03:23:29
【问题描述】:

我想实现在 SecureField 中显示和隐藏密码的功能。 下面是 SecureField 的代码 我添加了按钮,该按钮将被检测到以显示和隐藏 SecureField 中的文本。 但是 swiftUI 没有类似 isSecureTextEntry 的功能 除了在 TextfieldSecureField here

之间切换还有其他方法吗
SecureField(placeholder, text: $textValue, onCommit: {
    onReturn?()
})
.onTapGesture {
    onBegin?()
}
.keyboardType(keyboardType)
.font(Font.label.bodyDefault)
.disableAutocorrection(true)
.frame(maxWidth: .infinity, maxHeight: 40)
.padding(.leading)

【问题讨论】:

  • 链接选项是最好的选择,除非你想进入比这复杂得多的UIViewRepresentable

标签: swiftui securefield


【解决方案1】:

这并不像应有的那么简单。其中一个答案非常接近,但它并没有完全涵盖所有内容,因为它对@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
    }
}

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 2020-02-13
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    相关资源
    最近更新 更多