Disabling keyboard input when using a UITextField + UIPickerview

天涯浪子 提交于 2019-12-02 03:00:37

You can implement the UITextFieldDelegate method:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

To return false so that entering any character by hand would be prevented.

Paulo Mattos

This isn't an actual problem when running on a real iPhone device, since no keyboard will be available to do the typing :)

This is only seems like an issue when running on the iOS simulator, since you can then use your Mac keyboard as well.


Having said, you definitely should go with Mr. Hedgehog answer if you still want to block text input to your field.

If, besides blocking input, you may also want to hide the caret on the text field, also try this:

class PickerBasedTextField: UITextField {
    override func caretRect(for position: UITextPosition) -> CGRect {
        return CGRect.zero
    }
}

If you want to prevent user from using paste action, you can make a subclass of UITextField to override canPerformAction.

public class PickerUITextField: UITextField {
    override public func canPerformAction(_ action: Selector, withSender 
                                            sender: Any?) -> Bool {
        if action == #selector(UIResponderStandardEditActions.paste(_:)) {
            return false
        }
        return super.canPerformAction(action, withSender: sender)
    }
}

Here is a doc for list of actions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!