How to disable pasting in a TextField in Swift?

后端 未结 14 1465
予麋鹿
予麋鹿 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:18

    For Swift 5

    UIResponder​Standard​Edit​Actions has been added recently (iOS 10.0+) through which we can safely check if action is "paste" or not.

    import UIKit
    
    class NMTextField: UITextField {
        override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
            if action == #selector(UIResponderStandardEditActions.paste(_:)) {
                return false
            }
            return super.canPerformAction(action, withSender: sender)
        }
    }
    

提交回复
热议问题