【问题标题】:Showing clear button in a non-editable UITextField在不可编辑的 UITextField 中显示清除按钮
【发布时间】:2017-05-11 22:02:28
【问题描述】:

我正在向用户显示一个 UITextField,并且此文本字段中的文本由不同的控制器更新。

用户无法在此 UITextField 中输入内容。我通过执行以下操作确保了这一点:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return NO;
}

但我想在文本字段中显示清除图标,以便用户可以清除文本字段中的值。我通过执行以下操作来做到这一点:

_inputField.clearButtonMode = UITextFieldViewModeAlways;

但是当里面有文字时,清除按钮不会出现:(

知道我做错了什么吗?

【问题讨论】:

  • 只有在 textField 中有文本时才会显示 clearButton
  • 我正在以编程方式将文本添加到文本字段,但它没有显示出来
  • 根据文档:“覆盖视图仅在文本字段中编辑文本时显示。”因此,如果您未处于编辑模式,它将不会显示。也许试试_inputField.clearButtonMode = UITextFieldViewModeWhileEditing;
  • 只要放一个小按钮就可以了。
  • 您可以尝试将文本字段设置为第一响应者吗?

标签: ios objective-c


【解决方案1】:

试试这个:
customTextField.clearButtonMode = UITextFieldViewMode.Always

customTextField.clearsOnBeginEditing = true;

func textFieldShouldClear(textField: UITextField) -> Bool { 返回真 }

【讨论】:

    【解决方案2】:

    您需要创建一个自定义按钮并将其添加到文本字段的 rightView

    UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [clearButton setImage:[UIImage imageNamed:@"delete.png"] forState:UIControlStateNormal];
    [clearButton setFrame:CGRectMake(0,0,45,45)];
    // If you need action
    [clearButton addTarget:self action:@selector(clearTextField) forControlEvents:UIControlEventTouchUpInside];
    
    
     _inputField.rightViewMode = UITextFieldViewModeAlways;
     _inputField.rightView = clearButton;
     _inputField.rightView.hidden = NO;
    

    【讨论】:

      【解决方案3】:

      我认为您忘记添加 UITextFieldDelegate 并将委托设置为您的文本字段

      _inputField.delegate = self;
      

      【讨论】:

        猜你喜欢
        • 2016-04-27
        • 1970-01-01
        • 2016-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-19
        相关资源
        最近更新 更多