How to disable pasting in a TextField in Swift?

后端 未结 14 1450
予麋鹿
予麋鹿 2020-11-30 03:41

I\'ve got a TextField with a numberPad and the function runs only if it contains numbers.

The user will crash the app if they paste letters

14条回答
  •  遥遥无期
    2020-11-30 04:23

    You can just attach an IBAction to your Sent Events (editing changed) of your textfield to filter non numbers out of your string as you type as follow:

    @IBAction func changedTextAction(_ sender: UITextField) {
        sender.text = sender.text?.filter(\.isWholeNumber)
    }
    

    This will allow the user to paste into the field but it will filter all non digits from the string.

提交回复
热议问题