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))
}
}
}
おかしいところがもしあれば教えてください🙇♂️