[Swift] 限制TextField字數
實現UITextFieldDelegate內func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool這個方法
extension ViewController : UITextFieldDelegate{
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//最大字數
let maxLength = 16
let currentString: NSString = textField.text as! NSString
let newString: NSString =
currentString.replacingCharacters(in: range, with: string) as NSString
//return true時代表可以繼續輸入
return newString.length <= maxLength
}
}