Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable UITextField editing but still accept touch - Swift 3

I'm creating a UITextField that has a UIDatePicker as input. I don't want the textfield to be edited (copy, paste, cut and select text), but I only want to show UIDatePicker when users touch the UITextField and the chosen date will be displayed on UITextField.

I've tried to disable editing by using isUserInteractionEnabled = false, but the TextField doesn't give me response when I touch it.

What should I do to achieve it in Swift 3?

like image 605
user-unknown Avatar asked Jan 13 '17 15:01

user-unknown


1 Answers

To prevent the copy/paste menu appearing…

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    if dateTextField.isFirstResponder {
        DispatchQueue.main.async(execute: {
            (sender as? UIMenuController)?.setMenuVisible(false, animated: false)
        })
        return false
    }

    return super.canPerformAction(action, withSender: sender)
}

And implement…

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    // show UIDatePicker
    return false
}

This hides the menu before it has a chance to appear

like image 127
Ashley Mills Avatar answered Nov 14 '22 22:11

Ashley Mills