ios 禁用 UITextField 的简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/599733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:42:32  来源:igfitidea点击:

Easy way to disable a UITextField?

iphoneiosuitextfield

提问by CC.

Is there an easy way to disable a UITextFieldin code?

有没有一种简单的方法来禁用UITextField代码?

My app has 12 UITextFieldthat are all turned on by default, but when a change is detected in my Segment Control I want to disable some of the UITextFielddepending on what Segment the user picks.

我的应用程序有 12 个UITextField默认情况下全部打开,但是当在我的 Segment Control 中检测到更改时,我想UITextField根据用户选择的 Segment禁用其中的一些。

Just need to know how to disable it or make it non-editable?

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

Thanks

谢谢

回答by Joel Levin

In Objective-C:

在 Objective-C 中:

textField.enabled = NO;

In Swift:

在斯威夫特:

textField.isEnabled = false

Reference: UIControl.isEnabled

参考:UIControl.isEnabled

回答by Mariana B.

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:

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

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];

回答by Ankish Jain

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.

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

self.textfield.delegate=self;

and insert this delegate function:

并插入这个委托函数:

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

Thats it!

就是这样!

回答by Bhavesh

Make category on UIView.

在 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.

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

回答by onmyway133

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

你应该遵循这个方法UITextFieldDelegate返回false。这样文本字段仍然可以选择,但不可用于编辑和剪切

Code is in Swift 4

代码在 Swift 4 中

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