首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在SwiftUI中切换SecureField中的SecureField

在SwiftUI中切换SecureField中的SecureField
EN

Stack Overflow用户
提问于 2021-12-27 03:23:29
回答 1查看 1.9K关注 0票数 1

我想实现在SecureField中显示和隐藏密码的特性。下面是SecureField的代码,我添加了按钮,它将被检测到,以在SecureField中显示和隐藏文本。但是isSecureTextEntry没有类似于swiftUI的特性,在、Textfield、SecureField here之间有没有其他方式可以代替切换?

代码语言:javascript
运行
复制
SecureField(placeholder, text: $textValue, onCommit: {
    onReturn?()
})
.onTapGesture {
    onBegin?()
}
.keyboardType(keyboardType)
.font(Font.label.bodyDefault)
.disableAutocorrection(true)
.frame(maxWidth: .infinity, maxHeight: 40)
.padding(.leading)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-27 16:03:17

这并不像应该的那样简单。其中一个答案非常接近,但并不能涵盖所有内容,因为它的@FocusState实现很糟糕。iOS 15确实简化了这个字段的构造,因为有两个键: 1.使用.opacity()显示和隐藏字段;2.使用@FocusState实现两个字段之间的无缝转换。这种方法的唯一缺点是为了使转换无缝,必须将键盘限制为只与ASCII兼容的字符,因此忽略了一些语言,如俄语。

代码语言:javascript
运行
复制
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
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70491417

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档