How to disable pasting in a TextField in Swift?

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

    I have created a custom class for textField. I have handled the case when you want to enable/disable actions on textfield. You can customize the code as per your requirement. Set isActionsEnabled true/false for enable/disable actions on textfield.

    Prefer to use

    return super.canPerformAction(action, withSender: sender)

    instead of

    return true

    because returning true might cause a crash in some cases.

    Here is my code,

    open class MyTextFieldEffect : UITextField {
    
        var isActionsEnabled = true {
            didSet {
                reloadInputViews()
            }
        }
    
    override open func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
            /* disable particular actions
            if (action == #selector(paste(_:)) || action == #selector(copy(_:)) || action == #selector(select(_:)) || action == #selector(cut(_:)) || action == #selector(delete(_:)) || action == #selector(replace(_:withText:))  || action == #selector(select(_:))  || action == #selector(selectAll(_:)) || action == #selector(insertText(_:)) || action == #selector(draw(_:))) && !isActionsEnabled {
                return false
            }
            return super.canPerformAction(action, withSender: sender)
                                               */
    
           //disable all actions
            if !isActionsEnabled {
                return false
            }
    
            return super.canPerformAction(action, withSender: sender)
        }
    }
    

提交回复
热议问题