我以编程方式创建了一个搜索栏,并使用以下代码将其添加到我的 View 中:
- (void)viewDidLoad
{
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(xPositionForSearchBar, yPositionForSearchBar, widthForSearchBar, heightForSearchBar)];
UIView *bg = [[searchBar subviews] objectAtIndex:0];
searchBar.delegate = self;
searchBar.placeholder = @"Search record";
for(UIView *view in searchBar.subviews){
if([view isKindOfClass:[UITextField class]]){
UITextField *tf = (UITextField *)view;
tf.delegate = self;
break;
}
}
[bg removeFromSuperview];
[self.view addSubview: searchBar];
}
代码是用 UISearchBarDelegate 和 UITextFieldDelegate 实现的。
我试过用
- (void)searchBarCancelButtonClicked:(UISearchBar *)aSearchBar
{
NSLog(@"cancel clicked");
searchBar.text = @"";
[aSearchBar resignFirstResponder];
}
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
NSLog(@"clear");
[self performSelector:@selector(searchBarCancelButtonClicked:) withObject:searchBar afterDelay: 0.1];
return YES;
}
然而,当我点击“清除按钮”时,搜索栏内的文本根本没有被清除——一个里面有“X”的圆圈。
清除按钮在我在 IB 中实现时有效。想知道为什么?
请指点,非常感谢。
最佳答案
如果您将搜索栏放置在父 View 的边界之外,则可能会发生这种情况。然后,触摸不会正确地传递到您的 searchBar。这也会影响复制和粘贴等文本编辑控件。
关于ios - uisearchbar 上的清除按钮根本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12292471/