我以编程方式创建了一个搜索栏,并使用以下代码添加到我的视图中:
- (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 中实现它时,清除按钮有效。想知道为什么?
恳请指教,非常感谢。