LoginSignup
11
6

More than 5 years have passed since last update.

UITextFieldに最大文字数をStoryboardから設定させたい

Posted at

実装イメージ

パスワードの入力欄など、ある文字数以上入力させたくないケースって多いと思います。
でも、各画面でdelegateを設定して...とか面倒極まりない。

以下のように、storyboardから設定できたらいいですよね。

storyboard.png

拡張しましょう

UITextFieldを拡張します。

UITextField+maxLength.swift
import UIKit

private var maxLengths = [UITextField: Int]()

extension UITextField {

    @IBInspectable var maxLength: Int {
        get {
            guard let length = maxLengths[self] else {
                return Int.max
            }

            return length
        }
        set {
            maxLengths[self] = newValue
            addTarget(self, action: #selector(limitLength), for: .editingChanged)
        }
    }

    @objc func limitLength(textField: UITextField) {
        guard let prospectiveText = textField.text, prospectiveText.count > maxLength else {
            return
        }

        let selection = selectedTextRange
        let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)

        #if swift(>=4.0)
            text = String(prospectiveText[..<maxCharIndex])
        #else
            text = prospectiveText.substring(to: maxCharIndex)
        #endif

        selectedTextRange = selection
    }

}

おわりに

便利なExtensionを見つけては試して、気に入ったら取り入れていくスタイルで勉強を進めています。
どなたかの参考になれば幸いです。

11
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
6