【问题标题】:How can I change the color of a UITextField clearButton?如何更改 UITextField clearButton 的颜色?
【发布时间】:2012-03-28 20:11:34
【问题描述】:

我想更改当您在 UItextField 上书写时出现的 clearButton 的颜色。有什么建议吗?我不是高级界面开发人员,也不知道该怎么做。

【问题讨论】:

    标签: iphone objective-c xcode interface uitextfield


    【解决方案1】:

    您应该创建自己的 UIButton(带有图像,您需要一个所需按钮的 png),将其实例化并将此按钮放在 UITextField 的 rightView 中。

    CGFloat myWidth = 26.0f;
    CGFloat myHeight = 30.0f;
    UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, myWidth, myHeight)];
    [myButton setImage:[UIImage imageNamed:@"myButtonImage"] forState:UIControlStateNormal];
    [myButton setImage:[UIImage imageNamed:@"myButtonImage"] forState:UIControlStateHighlighted];
    
    [myButton addTarget:self action:@selector(doClear:) forControlEvents:UIControlEventTouchUpInside];
    
    myTextField.rightView = myButton;
    myTextField.rightViewMode = UITextFieldViewModeUnlessEditing;
    

    您可能需要使用(这些是示例值)来优化对齐方式:

    myButton.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    

    然后,您需要实现方法 -(void) doClear(id)sender;这将清除您的文本字段。

    【讨论】:

    • 非常感谢!我会试试看!
    • 如果您需要在“编辑时”显示按钮,您需要将rightViewMode 更改为UITextFieldViewModeWhileEditing
    • 我制作了一个示例清除按钮,您可以使用它。 chillysky.com/apps/Clear.png
    • @JackHumphries 你有这张图片的有效链接吗?
    【解决方案2】:

    斯威夫特 4

    我使用了 Giorgio 的答案,这就是我所采用的:

    let height = textField.bounds.height / 3
    let width = height + 10
    let rect = CGRect(x: 0, y: 0, width: width, height: height)
    
    let myButton = UIButton(frame: rect)
    
    myButton.setImage(UIImage(named: "clear button white"), for: .normal)
    
    textField.rightView = myButton
    textField.rightViewMode = .always
    
    myButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    

    正常的: enter image description here

    这个: enter image description here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-12
      • 1970-01-01
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      • 1970-01-01
      • 2015-03-12
      相关资源
      最近更新 更多