参考自BBCo
struct MyTextField:UIViewRepresentable{
let placeholder:String?
@Binding var text:String
@Binding var showText:Bool
let onCommit:()->Void
init(placeholder:String? = nil,
text:Binding<String>,
showText:Binding<Bool>,
onCommit:@escaping ()->Void = {}
){
self.placeholder = placeholder
self._text = text
self._showText = showText
self.onCommit = onCommit
}
func makeCoordinator() -> Coordinator {
Coordinator(view: self)
}
class Coordinator:NSObject,UITextFieldDelegate{
let parent:MyTextField
init(view:MyTextField) {
parent = view
}
func textFieldDidBeginEditing(_ textField: UITextField) {
print("开始输入")
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
print("textFieldShouldClear")
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
print("收起键盘")
textField.endEditing(true)
parent.onCommit()
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//if return true ,can update ,if return false cannot update
print(string)
print(range)
if string == "\n"{
textField.endEditing(true)
print("string == \n *********************** ")
}
return true
}
}
func makeUIView(context: Context) -> UITextField {
let view = UITextField()
view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
view.textColor = .black
view.tintColor = .black
view.text = text
view.placeholder = placeholder
view.adjustsFontSizeToFitWidth = true
view.borderStyle = .none
view.delegate = context.coordinator
view.clearButtonMode = .whileEditing
view.clearsOnBeginEditing = true
return view
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.isSecureTextEntry = !showText
print("updateUIView**************************** ")
}
}
网友评论