How to disable UITextField editing but still accep

2019-01-13 01:53发布

I'm making a UITextField that has a UIPickerView as inputView. Its all good, except that I can edit by copy, paste, cut and select text, and I don't want it. Only the Picker should modify text field.

I've learned that I can disable editing by setting setEnabled or setUserInteractionEnabled to NO. Ok, but the TextField stop responding to touching and the picker don't show up.

What can I do to achieve it?

14条回答
Juvenile、少年°
2楼-- · 2019-01-13 02:38

This would be the simplest of all:

in viewDidLoad:(set the delegate only for textfields which should not be editable.

self.textfield.delegate=self;

and insert this delegate function:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
return NO;
}

Thats it!

查看更多
【Aperson】
3楼-- · 2019-01-13 02:39

In swift 3+ :

class MyViewController: UIViewController, UITextFieldDelegate {

   override func viewDidLoad() {
      self.myTextField.delegate     = self
   }

   func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
      if textField == myTextField {
         // code which you want to execute when the user touch myTextField
      }
      return false
   }
}
查看更多
Deceive 欺骗
4楼-- · 2019-01-13 02:40

Translate the answer of Nick to swift:

P/S: Return false => the textfields cannot input, edit by the keyboard. It just can set text by code.EX: textField.text = "My String Here"

override func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    return false
}
查看更多
We Are One
5楼-- · 2019-01-13 02:42

In Swift:

func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    questionField.resignFirstResponder();
    // Additional code here
    return false
}
查看更多
相关推荐>>
6楼-- · 2019-01-13 02:42

Simply place a UIButton exactly over the entire UITextField with no Label-text which makes it "invisible". This button can receive and delegate touches instead of the Textfield and the content of the TextField is still visible.

查看更多
霸刀☆藐视天下
7楼-- · 2019-01-13 02:42

I used the solution provided by MrMage. The only thing I'd add is you should resign the UITextView as first responder, otherwise you're stuck with the text selected.

Here's my swift code:

class TouchableTextView : UITextView {

    override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
        self.resignFirstResponder()
        return false
    }

    override func shouldChangeTextInRange(range: UITextRange, replacementText text: String) -> Bool {
        self.resignFirstResponder()
        return false
    }

}
查看更多
登录 后发表回答