SwiftUI 有两种不同形式的文本字段,一种是隐藏输入的 SecureField 和不隐藏输入的 TextField。有没有一种方法可以创建一个单一视图,该视图接受一个参数来创建两种类型,同时重复尽可能少的代码,而不是创建两个单独的视图?
您只需使用View您想要的所有代码创建一个SecureTextField,然后TextField您所要做的就是在HybridTextField需要的地方调用它。
import SwiftUI
struct HybridTextFieldUsageView: View {
@State var password: String = "password"
var body: some View {
//Use this anywhere in your code
HybridTextField(text: $password, titleKey: "password")
}
}
///Contains all the code for the Secure and regular TextFields
struct HybridTextField: View {
@Binding var text: String
@State var isSecure: Bool = true
var titleKey: String
var body: some View {
HStack{
Group{
if isSecure{
SecureField(titleKey, text: $text)
}else{
TextField(titleKey, text: $text)
}
}.textFieldStyle(.roundedBorder)
.animation(.easeInOut(duration: 0.2), value: isSecure)
//Add any common modifiers here so they dont have to be repeated for each Field
Button(action: {
isSecure.toggle()
}, label: {
Image(systemName: !isSecure ? "eye.slash" : "eye" )
})
}//Add any modifiers shared by the Button and the Fields here
}
}
struct HybridTextField_Previews: PreviewProvider {
static var previews: some View {
HybridTextFieldUsageView()
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7064 次 |
| 最近记录: |