How to disable pasting in a TextField in Swift?

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

    I agree with Leonardo Savio Dabus, if I were you I'd use string checking and just give out a warning, it makes things easier. BUT, if disabling paste option is a fancy feature you really want to put into your app, then you need to do more work. I'll provide the steps below.

    Step 1: You need to create another class which extends the UITextField. In this example, I made my CustomUITextField.

    import Foundation
    import UIKit  //Don't forget this
    
    class CustomUITextField: UITextField {
       override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
            if action == #selector(UIResponderStandardEditActions.paste(_:)) {
                return false
            }
            return super.canPerformAction(action, withSender: sender)
       }
    }
    

    Step 2: Wire the storyboard with your ViewController. You need to declare an IBOutlet as in normal case:

    @IBOutlet var textFieldA: CustomUITextField?
    

    Wire the circle next to the @IBOutlet to the TextField in the storyboard. THEN, this is important and easy to be ignored:

    • Go to your storyboard
    • Click the target TextField
    • Select Identity Inspector (the 3rd one)
    • Change the class to CustomUITextField

    Quick snapshot is provided below.

    enter image description here

    That's it, hope this works.

    Credit:

    Main reference

    If you want to know more about the behavior of canPerformAction method, though it's an Objective-C version, the concepts are shared here.

提交回复
热议问题