gpt4 book ai didi

text - 如何声明文本字段只能包含整数?

转载 作者:IT王子 更新时间:2023-10-29 05:08:45 25 4
gpt4 key购买 nike

在 swift 中,我正在尝试制作一个允许启用按钮的文本字段,但仅当文本字段包含整数时。我该怎么做?

最佳答案

两件事:

  1. 指定键盘类型以仅显示数字小键盘。因此,将 keyboardType 设置为 .numberPad。然而,这不足以阻止用户在文本字段中输入无效字符。例如,用户在使用 iPad 时仍然可以粘贴文本或切换键盘。

  2. 指定文本字段的委托(delegate)并实现 shouldChangeCharactersInRange,它将不接受除数字 09 以外的任何字符:

    class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
    super.viewDidLoad()

    // you can set the following two properties for the text field in Interface Builder, if you'd prefer

    textField.delegate = self
    textField.keyboardType = .numberPad
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let invalidCharacters = CharacterSet(charactersIn: "0123456789").inverted
    return string.rangeOfCharacter(from: invalidCharacters) == nil
    }

    // or, alternatively:
    //
    // func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    // return string.range(of: "^\\d*$", options: .regularExpression) != nil
    // }

    }

对于 Swift 2 版本,请参阅此答案的先前修订版。

关于text - 如何声明文本字段只能包含整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26919854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com