How to disable pasting in a TextField in Swift?

后端 未结 14 1336
予麋鹿
予麋鹿 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:20
    class CustomUITextField: UITextField {
        override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
            if action == #selector(cut(_:)) ||
               action == #selector(copy(_:)) ||  
               action == #selector(UIResponderStandardEditActions.paste(_:)) || 
               action == #selector(UIResponderStandardEditActions.select(_:)) || 
               action == #selector(UIResponderStandardEditActions.selectAll(_:)) || 
               action == #selector(UIResponderStandardEditActions.delete(_:)) ||  
               action == #selector(UIResponderStandardEditActions.makeTextWritingDirectionLeftToRight(_:)) ||  
               action == #selector(UIResponderStandardEditActions.makeTextWritingDirectionRightToLeft(_:)) || 
               action == #selector(UIResponderStandardEditActions.toggleBoldface(_:)) || 
               action == #selector(UIResponderStandardEditActions.toggleItalics(_:)) || 
               action == #selector(UIResponderStandardEditActions.toggleUnderline(_:)) || 
               action == #selector(UIResponderStandardEditActions.increaseSize(_:)) || 
               action == #selector(UIResponderStandardEditActions.decreaseSize(_:)) 
            {
                 return false
            };
            return true
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题