UISearchBar取消按钮
在iOS 5上使用带有showCancelButton = YES的UISearchBar。希望取消按钮在键盘下降时保持启用状态。 使用下面的代码似乎不工作:
for (id subView in self.searchControl.subviews)
{
if ([subView isKindOfClass:[UIButton class]])
{
UIButton *cancelButton = (UIButton *)subView;
[cancelButton setEnabled:YES];
break;
}
}
子视图实际上是一个UINavigationButton,它看起来并不是从UIButton中分类出来的。 我在这里想念什么??????? 在Apple文档中也找不到UINavigationButton类中的任何信息。
设置您的搜索栏委托,并放置此代码。
- (void) searchBarSearchButtonClicked:(UISearchBar*) theSearchBar
{
[theSearchBar resignFirstResponder];
[theSearchBar setShowsCancelButton:NO animated:YES];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:YES animated:YES];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
[searchBar setShowsCancelButton:NO animated:YES];
}
Swift 3.0
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar .resignFirstResponder()
searchBar.setShowsCancelButton(false, animated: true)
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
searchBar.setShowsCancelButton(false, animated: true)
}
只是为了改进Kurt Spindler在他的帖子上所说的话。 虽然这可能不是优越的,但它更受控制。 我使用dispatch来做同样的事情。
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
for (UIView *subview in searchBar.subviews)
{
if ([subview isKindOfClass:[UIButton class]])
{
int64_t delayInSeconds = .001;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
UIButton * cancelButton = (UIButton *)subview;
[cancelButton setEnabled:YES];
});
break;
}
}
}
这应该适用于需要帮助保持取消的每个人。 确保稍后使用取消或点击搜索来隐藏它。
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
[searchBar resignFirstResponder];
[searchBar setShowsCancelButton:NO animated:YES];
}
我在搜索栏取消按钮上放置了一个自定义取消按钮。
链接地址: http://www.djcxy.com/p/44275.html