在iPhone上的联系人应用程序中,如果你输入一个搜索词,然后点击“搜索”按钮,键盘将隐藏,但取消按钮仍可用。在我的应用程序中,当我调用resignFirstResponder时,取消按钮被禁用。
有人知道如何在保持取消按钮处于启用状态的同时隐藏键盘吗?
我使用以下代码:
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
}
键盘滑出视线,但搜索文本字段右侧的" cancel“按钮被禁用,因此我无法取消搜索。联系人应用程序将“取消”按钮保持在启用状态。
我认为一种解决方案可能是深入研究searchBar对象并对实际的文本字段调用resignFirstResponder,而不是搜索栏本身。
感谢您提供的任何意见。
发布于 2012-04-02 06:33:56
尝尝这个
for(id subview in [yourSearchBar subviews])
{
if ([subview isKindOfClass:[UIButton class]]) {
[subview setEnabled:YES];
}
}
发布于 2013-08-09 23:53:47
这种方法在iOS7中有效。
- (void)enableCancelButton:(UISearchBar *)searchBar
{
for (UIView *view in searchBar.subviews)
{
for (id subview in view.subviews)
{
if ( [subview isKindOfClass:[UIButton class]] )
{
[subview setEnabled:YES];
NSLog(@"enableCancelButton");
return;
}
}
}
}
(还要确保在使用_searchBar resignFirstResponder之后在任何地方调用它。)
发布于 2012-09-13 20:21:14
当您开始滚动表格而不是点击“搜索”按钮时,接受的解决方案将不起作用。在这种情况下,“取消”按钮将被禁用。
这是我的解决方案,每次使用KVO禁用"Cancel“按钮时都会重新启用该按钮。
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// Search for Cancel button in searchbar, enable it and add key-value observer.
for (id subview in [self.searchBar subviews]) {
if ([subview isKindOfClass:[UIButton class]]) {
[subview setEnabled:YES];
[subview addObserver:self forKeyPath:@"enabled" options:NSKeyValueObservingOptionNew context:nil];
}
}
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
// Remove observer for the Cancel button in searchBar.
for (id subview in [self.searchBar subviews]) {
if ([subview isKindOfClass:[UIButton class]])
[subview removeObserver:self forKeyPath:@"enabled"];
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
// Re-enable the Cancel button in searchBar.
if ([object isKindOfClass:[UIButton class]] && [keyPath isEqualToString:@"enabled"]) {
UIButton *button = object;
if (!button.enabled)
button.enabled = YES;
}
}
https://stackoverflow.com/questions/9968595
复制相似问题