Easy way to disable a UITextField?

前端 未结 5 1363
一向
一向 2020-11-29 08:01

Is there an easy way to disable a UITextField in code?

My app has 12 UITextField that are all turned on by default, but when a change is de

相关标签:
5条回答
  • 2020-11-29 08:29

    This would be the simplest of all , when you multiple textfields too:

    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 08:32

    In Objective-C:

    textField.enabled = NO;
    

    In Swift:

    textField.isEnabled = false
    

    Reference: UIControl.isEnabled

    0 讨论(0)
  • 2020-11-29 08:36

    You should conform to UITextFieldDelegate and return false in this method. This way the text field is still selectable, but it is not available for editing and cutting

    Code is in Swift 4

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
      return false
    }
    
    0 讨论(0)
  • 2020-11-29 08:44

    Make category on UIView.

    add following methods in that category.

    -(void)disable {
        self.alpha = 0.5;
        self.userInteractionEnabled = FALSE;
    }
    
    -(void)enable {
        self.alpha = 1.0;
        self.userInteractionEnabled = TRUE;
    }
    

    then just call

    yourTextField.disable();
    

    Actually,You can use this on any view that you want.

    0 讨论(0)
  • 2020-11-29 08:47

    If you also want to indicate that the text field is disabled you should add more code:

    if using UITextBorderStyleRoundedRect, you can only gray out text:

    textField.enabled = NO;
    textField.textColor = [UIColor lightGrayColor];
    

    if using any other style, you can also gray out background:

    textField.enabled = NO;
    textField.backgroundColor = [UIColor lightGrayColor];
    
    0 讨论(0)
提交回复
热议问题