利用textField(_:shouldChangeCharactersIn:replacementString:) 控制文字輸入的字數

定義 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:) 加入新輸入的字串,得到新的字串後,即可判斷字串長度,決定是否可以輸入。

參考

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com