2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Swift】テキストフィールド数値のみの入力制限

Posted at

iOSでよく扱う入力制限についての備忘録です

@IBOutlet private weak var quantityTextField: UITextField!

override func viewDidLoad() {
        super.viewDidLoad()

        quantityTextField.delegate = self
}

//省略

extension ViewController: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        guard let text = textField.text else {
            return false
        }
        
        if textField === quantityTextField {
            //数値のみチェック
            guard string.isEmpty || !string.match(#"^\d+$"#).isEmpty else {
                return false
            }
            //レンジを取得
            guard let textRange = Range(range, in: text) else {
                return false
            }
            // `textRange`の範囲をstringへ置換
            let updatedText = text.replacingCharacters(in: textRange, with: string)
            //桁数チェック
            guard
                updatedText.count < 6 else {
                return false
            }
            //最初に0は拒否
            guard updatedText.match(#"^0"#).isEmpty else {
                return false
            }
        }
        
        return true
    }
    
}

正規表現を扱うのでStringクラスを拡張

extension String {
    func match(_ pattern: String) -> [String] {
        guard let regex = try? NSRegularExpression(pattern: pattern),
              let matched = regex.firstMatch(in: self, range: NSRange(location: 0, length: self.count))
        else { return [] }
        return (0 ..< matched.numberOfRanges).map {
            NSString(string: self).substring(with: matched.range(at: $0))
        }
    }
}

おかしいところがもしあれば教えてください🙇‍♂️

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?