TextFieldで簡単に文字数制限
動画は入力7文字制限です。
GIF
githubにXcode9.3バージョンのソースあります。
https://github.com/daisukenagata/PasswordTextField
使い方
好きなViewControllerにUITextFieldを配置
アトリビュートインスペクタのTag設定で文字数を設定
2018/5/11 viewDidLoadメソッド内でcodeに変換しました。
ViewController内の編集判定コード
このメソッドは毎回呼ばれるTextFieldのデフォルトのメソッドです。
ここで複数UITextFieldを設定していても、そのUITextFieldのtag番号と文字列で判定できます。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
passTextField.pass(st:passTextField.text!, tag: passTextField.tag, textField: textField)
return true
}
キーボードが下がる時も文字列制限を実施します。
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
passTextField.pass(st: passTextField.text!, tag: passTextField.tag, textField: textField)
textField.resignFirstResponder()
return false
}
ペースト等制限のコード
カーソル非表示
override func caretRect(for position: UITextPosition) -> CGRect { return CGRect.zero }
範囲選択非表示
override func selectionRects(for range: UITextRange) -> [Any] { return [] }
コピー・ペースト・非表示
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { return false }
文字数制限のコード
st.prefix(tag)で指定の数字まで文字読み込んでいます。
func pass(st:String,tag:Int,textField:UITextField) {
if st.count >= tag {
textField.text = String((st.prefix(tag)))
}
}
以上です。ありがとうございました。