UITextField clearButtonMode color

匿名 (未验证) 提交于 2019-12-03 01:31:01

问题:

can I change the color of the clearButtonMode on a textField?

theTextField.clearButtonMode = UITextFieldViewModeWhileEditing 

shows an x that is grey dark color to delete the textField,

but can i show this button with white color?

thanks

回答1:

You'll need to create your own clear button image in this case. I would suggest taking a screenshot of the clear button and editing in photoshop.

You can take that image and create a UIButton with the image dimensions. From there you can set it as the UITextField's rightView. Like so:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setImage:[UIImage imageNamed:@"clear_button.png"] forState:UIControlStateNormal]; [button setFrame:CGRectMake(0.0f, 0.0f, 15.0f, 15.0f)]; // Required for iOS7 theTextField.rightView = button; theTextField.rightViewMode = UITextFieldViewModeWhileEditing; 

I typed that without syntax checking and what not so you'll want to check it out before running it. You'll also want to replace clear_button.png with whatever your image name is.

You'll also need to write your own method to clear the text field.



回答2:

A cleaner way is to implement a category on UITextField with this method:

- (void)modifyClearButtonWithImage:(UIImage *)image {     UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];     [button setImage:image forState:UIControlStateNormal];     [button setFrame:CGRectMake(0.0f, 0.0f, 15.0f, 15.0f)];     [button addTarget:self action:@selector(clear:) forControlEvents:UIControlEventTouchUpInside];     self.rightView = button;     self.rightViewMode = UITextFieldViewModeWhileEditing; }  -(IBAction)clear:(id)sender{     self.text = @""; } 


回答3:

Swift version :

extension UITextField {     func modifyClearButtonWithImage(image : UIImage) {     let clearButton = UIButton(type: .Custom)     clearButton.setImage(image, forState: .Normal)     clearButton.frame = CGRectMake(0, 0, 40, 40)     clearButton.contentMode = .ScaleAspectFit     clearButton.addTarget(self, action: #selector(UITextField.clear(_:)), forControlEvents: .TouchUpInside)     self.rightView = clearButton     self.rightViewMode = .WhileEditing }          func clear(sender : AnyObject) {         self.text = ""     }  } 


回答4:

At the time you're configuring the textField, use:

let clearButton : UIButton = textField.value(forKey: "_clearButton") as! UIButton let image = UIImage(named: "ClearWhite")  clearButton.setImage(image, for: .normal) clearButton.backgroundColor = UIColor.clear 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!