我在同一视图中有两个UITextFields
,我希望每个人都有特定的条件。第一个只需要42
个字符长字符串,第二个只能接受0123456789
和.
。
我使用textField(_:shouldChangeCharactersIn:replacementString:)
来设置第一个文本字段,但是如何设置第二个文本字段而不同时具有这两个条件?
TextFields:
@IBOutlet weak var firstTextField: UITextField!
@IBOutlet weak var secondTextField: UITextField!
第一个TextField条件:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
let newLength = text.count + string.count - range.length
return newLength == 42
}
第二个TextField条件?
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let aSet = NSCharacterSet(charactersIn:".0123456789").inverted
let compSepByCharInSet = string.components(separatedBy: aSet)
let numberFiltered = compSepByCharInSet.joined(separator: "")
return string == numberFiltered
}
我无法使用textField(_:shouldChangeCharactersIn:replacementString:)
两次,所以我可以这样做吗?
答案 0 :(得分:1)
使用简单的
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == firstTextField{ // its Identify your textfield
guard let text = textField.text else { return true }
let newLength = text.count + string.count - range.length
return newLength == 42
}else{
let aSet = NSCharacterSet(charactersIn:".0123456789").inverted
let compSepByCharInSet = string.components(separatedBy: aSet)
let numberFiltered = compSepByCharInSet.joined(separator: "")
return string == numberFiltered
}
return true
}