我想实现在SecureField中显示和隐藏密码的特性。下面是SecureField的代码,我添加了按钮,它将被检测到,以在SecureField中显示和隐藏文本。但是isSecureTextEntry没有类似于swiftUI的特性,在、Textfield、和SecureField here之间有没有其他方式可以代替切换?
SecureField(placeholder, text: $textValue, onCommit: {
onReturn?()
})
.onTapGesture {
onBegin?()
}
.keyboardType(keyboardType)
.font(Font.label.bodyDefault)
.disableAutocorrection(true)
.frame(maxWidth: .infinity, maxHeight: 40)
.padding(.leading)
发布于 2021-12-27 16:03:17
这并不像应该的那样简单。其中一个答案非常接近,但并不能涵盖所有内容,因为它的@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
}
}
https://stackoverflow.com/questions/70491417
复制相似问题