I have a code below that will have an UIAlertController
with an UITextField
that will only accept numbers.
class ViewController: UIViewController, UITextFieldDelegate {
let priceText = UILabel()
static let DefaultText = "Click to enter price"
static let DefaultPlaceHolder = "In dollar"
override func viewDidLoad() {
super.viewDidLoad()
priceText.text = ViewController.DefaultText
view.addSubview(priceText)
priceText.translatesAutoresizingMaskIntoConstraints = false
priceText.backgroundColor = .yellow
NSLayoutConstraint.activate([
priceText.centerXAnchor.constraint(equalTo: view.centerXAnchor),
priceText.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
priceText.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(openEnterPriceDialog)))
priceText.isUserInteractionEnabled = true
}
@objc private func openEnterPriceDialog() {
let alert = UIAlertController(
title: "Enter Price",
message: "The value you want to sell",
preferredStyle: UIAlertController.Style.alert)
alert.addTextField {
$0.placeholder = ViewController.DefaultPlaceHolder
$0.keyboardType = .numberPad
$0.delegate = self
}
alert.addAction(UIAlertAction(
title: "Cancel",
style: UIAlertAction.Style.default,
handler: nil))
alert.addAction(UIAlertAction(
title: "Submit",
style: UIAlertAction.Style.default,
handler: nil }))
self.present(alert, animated: true, completion: nil)
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let invalidCharacters = CharacterSet(charactersIn: "0123456789").inverted
return string.rangeOfCharacter(from: invalidCharacters) == nil
}
}
extension UITextField {
open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return action == #selector(UIResponderStandardEditActions.cut) || action == #selector(UIResponderStandardEditActions.copy)
}
}
However, it is still somehow allow key like 000
or even 01230
, which is not a nice number.
I would be okay with 0
or 1230
, but not something start with 0
.
How could I achieve that?
ps: most of stackoverflow answer like How can I declare that a text field can only contain an integer? only check to ensure digit from 0123456789 can be accepted, but still allow things like 00
, or 01230
.