iosswiftuikituitextfield

Disable AutoFill, Speak and Spell for UITextField


I want to disable basically any actions with text in a UITextField. That also means user can't Speak, Spell or AutFill the content. Here's the code I'm using for my custom UITextField:

class GradientTextField: UITextField {
    var actionEnabled: Bool = true
...
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if actionEnabled {
            return super.canPerformAction(action, withSender: sender)
        } else {
            return false
        }
    }
    
    override func selectionRects(for range: UITextRange) -> [UITextSelectionRect] {
        return []
    }
    
    override func caretRect(for position: UITextPosition) -> CGRect {
        return .zero
    }

And yet it still does allow speaking, spelling & autofilling its content. Look at the screenshot below:

UITextFieldScreenshot

In addition, I want to prevent the user from using a cursor there. So symbol deletion and input are done in the same order (e.g. if I type in 1234, I cannot delete 3 or 2 to make it 14).

Could you help me find out how to do it?


Solution

  • A solution could be put a UIButton on top of UITextField to block interactions. So when user tap the button, all we have to do is make UITextField become first responder

    enter image description here

    class DisableTextField: UIViewController {
    
        @IBOutlet weak var textfield: UITextField!
        @IBOutlet weak var button: UIButton!
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Do any additional setup after loading the view.
        }
    
    
        @IBAction func onTap(_ sender: Any) {
            textfield.becomeFirstResponder()
        }
    
    }