首先需要继承 UITextFieldDelegate
class TestViewController: UIViewController,UITextFieldDelegate{ }
添加事件委托
textField.delegate = self
点击输入框时触发以下事件:
func textFieldDidBeginEditing(_ textField: UITextField){ }
我的需求为输入一百以内最多为两位小数,使用以下方式对输入的值进行实时监控
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { var newString = (textField.text! as NSString).replacingCharacters(in: range, with: string) let expression = "^[0-9]*(?:\.[0-9]{0,2})?$" do { let regex: NSRegularExpression = try NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.caseInsensitive) let numberOfMatches = regex.matches(in: newString, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, newString.characters.count)) if numberOfMatches.count == 0{ return false }else{ if newString != "" { if newString[newString.startIndex] == "." { newString = "0" + newString } if newString[newString.index(before: newString.endIndex)] == "." { newString = newString + "0" } if (Double(newString)! > 100.0){ account_textfield.text = "100" return false } } return true } } catch { return false } }
通过return值对输入框的值进行控制,return false则放弃编辑,输入框内容不会变更