How to disable UITextField editing but still accept touch?

后端 未结 15 2293
误落风尘
误落风尘 2020-11-29 19:55

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 te

相关标签:
15条回答
  • 2020-11-29 20:12

    Using the textfield delegate, there's a method

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    

    Return NO from this, and any attempt by the user to edit the text will be rejected.

    That way you can leave the field enabled but still prevent people pasting text into it.

    0 讨论(0)
  • 2020-11-29 20:14

    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
    }
    
    0 讨论(0)
  • 2020-11-29 20:16

    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
       }
    }
    
    0 讨论(0)
  • 2020-11-29 20:16

    I used :

    [self.textField setEnabled:NO];
    

    and its work fine

    0 讨论(0)
  • 2020-11-29 20:17

    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!

    0 讨论(0)
  • 2020-11-29 20:20

    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.

    0 讨论(0)
提交回复
热议问题