如何在UITextField中添加自定义清除按钮?

时间:2023-01-19 16:35:16

I want to resize the default clear button of UITextField. After I googled a lot, I came to know there is no way to modify it.

我想调整UITextField的默认清除按钮的大小。经过google搜索后,我才知道无法修改它。

So I decided to go with Custom option ie, by adding UIButton to text field.I found some code from S.O, but nothing works for me. These are the links which I referred.

所以我决定使用自定义选项,即将UIButton添加到文本字段。我从S.O找到了一些代码,但没有任何对我有用。这些是我提到的链接。

So please suggest some solution which behaves exactly as default clear button of UITextField

所以请建议一些解决方案,其行为与UITextField的默认清除按钮完全相同

Any help will be appreciated.

任何帮助将不胜感激。

Thanks in advance.

提前致谢。

2 个解决方案

#1


3  

In addition to the jake9115 response, you can emulate the clearbutton behavior by using the UITextFieldDelegate callbacks.

除了jake9115响应之外,您还可以使用UITextFieldDelegate回调来模拟clearbutton行为。

You can try in this way:
Show the button when -textFieldDidBeginEditing: is called
Hide the button when -textFieldDidEndEditing: is called
Hide the button if in -(BOOL)textFieldShouldClear:(UITextField*)textField the length of the textField's text is 0.

你可以这样尝试:当-textFieldDidBeginEditing:被调用时显示按钮当-textFieldDidEndEditing:被调用时隐藏按钮隐藏按钮if - (BOOL)textFieldShouldClear:(UITextField *)textField textField文本的长度为0。

#2


2  

Why not just make a button that sets the TextView's value to ""?

为什么不只是创建一个将TextView的值设置为“”的按钮?

- (IBAction)button:(id)sender {
_myTextView.text = "";
}

#1


3  

In addition to the jake9115 response, you can emulate the clearbutton behavior by using the UITextFieldDelegate callbacks.

除了jake9115响应之外,您还可以使用UITextFieldDelegate回调来模拟clearbutton行为。

You can try in this way:
Show the button when -textFieldDidBeginEditing: is called
Hide the button when -textFieldDidEndEditing: is called
Hide the button if in -(BOOL)textFieldShouldClear:(UITextField*)textField the length of the textField's text is 0.

你可以这样尝试:当-textFieldDidBeginEditing:被调用时显示按钮当-textFieldDidEndEditing:被调用时隐藏按钮隐藏按钮if - (BOOL)textFieldShouldClear:(UITextField *)textField textField文本的长度为0。

#2


2  

Why not just make a button that sets the TextView's value to ""?

为什么不只是创建一个将TextView的值设置为“”的按钮?

- (IBAction)button:(id)sender {
_myTextView.text = "";
}