简单的方法来禁用UITextField?

时间:2009-03-01 12:16:20

标签: iphone ios uitextfield

是否有一种简单的方法可以禁用代码中的UITextField

我的应用有12 UITextField默认情况下全部开启,但是当我的细分控制中检测到更改时,我想根据用户选择的细分来禁用部分UITextField

只需要知道如何禁用它或使其不可编辑?

由于

5 个答案:

答案 0 :(得分:103)

在Objective-C中:

textField.enabled = NO;

在斯威夫特:

textField.isEnabled = false

参考:UIControl.isEnabled

答案 1 :(得分:29)

如果您还想表明文本字段已被禁用,则应添加更多代码:

如果使用UITextBorderStyleRoundedRect,则只能灰显文本:

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

如果使用任何其他样式,您也可以使背景变灰:

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

答案 2 :(得分:11)

当你有多个文本字段时,这将是最简单的:

viewDidLoad中的

:(仅为不应编辑的文本字段设置委托。

self.textfield.delegate=self;

并插入此委托函数:

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

多数民众赞成!

答案 3 :(得分:1)

在UIView上制作类别。

在该类别中添加以下方法。

 @media only screen  and (min-width: 200px) and (max-width: 350px)
    {
        .button_orange_extended
        {
            margin-left:0px;
        }
    }   /*Media query for one specific screen width*/



  @media only screen  and (min-width: 360px) and (max-width: 400px)
    {
        .button_orange_extended
        {

            margin-left:30px;
        }
    } /*Another Media query for  specific screen width*/



  @media only screen  and (min-width: 400px) and (max-width: 450px)
    {
        .button_orange_extended
        {

            margin-left:80px;
        }
    }

然后打电话

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

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

实际上,您可以在任何您想要的视图上使用它。

答案 4 :(得分:-3)

您应该符合UITextFieldDelegate并在此方法中返回false。这样,文本字段仍然可以选择,但它不能用于编辑和剪切

代码在Swift 4中

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  return false
}
相关问题