如何在UITextFieldDelegate的方法中提前获取te
如果要实时检测UITextField值在界面输入的变化,可以设置UITextField.delegate
并实现UITextFieldDelegate的以下方法
func textField(_ textField:UITextField, shouldChangeCharactersIn range:NSRange, replacementString string:String) ->Bool{
}
但在该方法中直接获取textField.text无法得到更新后的值,如果需要获取,可利用shouldChangeCharactersIn与replacementString,结合textField.text(旧的值)计算得出。
直接上代码:
func textField(_ textField:UITextField, shouldChangeCharactersIn range:NSRange, replacementString string:String) ->Bool{
var text = textField.text!
let range1 = text.toRange(range)//需要扩展String类,见以下代码
//text就是新值
text = text.replacingCharacters(in: range1!, with: string)
return true
}
//还需要为String添加扩展,实现NSRange向Range的转换
public extension String {
public func toRange(_ range: NSRange) -> Range? {
guard let from16 = utf16.index(utf16.startIndex, offsetBy: range.location, limitedBy: utf16.endIndex) else { return nil }
guard let to16 = utf16.index(from16, offsetBy: range.length, limitedBy: utf16.endIndex) else { return nil }
guard let from = String.Index(from16, within: self) else { return nil }
guard let to = String.Index(to16, within: self) else { return nil }
return from ..< to
}
}