2
Help us understand the problem. What are the problem?

posted at

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

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))
        }
    }
}

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

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
2
Help us understand the problem. What are the problem?