问题描述
我有一个UISearchBar,我已经为UiControlStateNormal设置了自定义UISearchBarIconClear。
I have a UISearchBar for which I have set a custom UISearchBarIconClear for UiControlStateNormal.
[mySearchBar setImage:myImage forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
此部分可以正常工作但不幸的是,当点击清除按钮时,它会改变我设置的图像,原始的默认灰色。
This part works as it should but unfortunately when tapping the clear button, it changes from the image I set, to the original default gray one.
我已经尝试为UIControlStateHighlighted设置图像,但显然这不起作用。
I have tried setting the image for UIControlStateHighlighted, but apparently that does not work.
实际上表明
如果您无法将其设置为突出显示状态,那么为默认状态设置自定义按钮的重点是什么?我错过了什么吗?任何想法或变通方法都表示赞赏,谢谢!
What's the point of setting a custom button for the default state if you can't set it for the highlighted state? Am I missing something? Any thoughts or workarounds appreciated, thanks!
推荐答案
今天早些时候遇到同样的问题,这是我非常难看的解决方法我可能不会自己使用。
Came across the same issue a little bit earlier today, here is my really ugly workaround that I probably wouldn't use myself.
for(UIView *subView in searchBar.subviews) {
if([subView isKindOfClass: [UITextField class]]){
UITextField *searchField = (UITextField *)subView;
CGFloat myWidth = 26.0f;
CGFloat myHeight = 30.0f;
UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, myWidth, myHeight)];
[myButton setImage:[UIImage imageNamed:@"searchbariconclear"] forState:UIControlStateNormal];
[myButton setImage:[UIImage imageNamed:@"searchbariconclear"] forState:UIControlStateHighlighted];
[myButton addTarget:self action:@selector(clearsearchbar) forControlEvents:UIControlEventTouchUpInside];
searchField.rightView = myButton;
searchField.rightViewMode = UITextFieldViewModeAlways;
searchField.clearButtonMode = UITextFieldViewModeNever;
}
}
然后..
- (void)clearsearchbar {
for(UIView *subView in searchBar.subviews) {
if([subView isKindOfClass: [UITextField class]]){
UITextField *searchField = (UITextField *)subView;
searchField.text = nil;
}
}
}
此方法存在三个问题。 。
Three problems with this approach..
-
由于我们正在挖掘搜索栏的子视图内部,因此可能会在操作系统更新时终止。
Since we're digging around inside the subviews of the searchbar it could break some day with an OS update.
这与UISearchBarIconClear的行为完全不同,因为清晰的图标始终可见..您可能尝试使用此方法测试其他UITextFieldViewModes,我没有主要是因为,据我所知,其他人都不会因为某种原因或其他原因而理想。
This doesn't behave exactly like UISearchBarIconClear, in that the clear icon will always be visible.. You could potentially try testing with other UITextFieldViewModes using this approach, I didn't mainly because, from what I know none of the others would be ideal here, for some reason or the other.
也许这只是我,但我不要认为在尝试解决问题时引入两个问题的东西是一种解决方案。 : - )
Maybe it's just me, but I don't really think that something that introduces two problems when trying to solve one, is a solution. :-)
如果有人有更好的方法来解决这个问题,我也很乐意听。
If anyone has a better way of tackling this problem, I'd love to hear it too.
这篇关于为UIControlStateHighlighted定制UISearchBarIconClear不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!