利用textField(_:shouldChangeCharactersIn:replacementString:) 控制文字輸入的字數
Published in
Jun 8, 2018
定義 protocol UITextFieldDelegate 的 textField(_:shouldChangeCharactersIn:replacementString:),回傳 true 允許文字輸入,回傳 false 讓文字不能輸入。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { var result = false if let text = textField.text,
let range = Range(range, in: text) { let newText = text.replacingCharacters(in: range, with: string) if newText.count < 10 { result = true } } return result}
利用 String 的 replacingCharacters(in:with:) 加入新輸入的字串,得到新的字串後,即可判斷字串長度,決定是否可以輸入。
參考