我想在没有故事板的情况下将UISearchBar添加到我的视图控制器中,因此我以编程方式将其添加为子视图。我已经设置了委托,但我似乎无法通过单击搜索按钮来解除键盘。
这是我的代码:
@interface ViewController : UIViewController <UISearchBarDelegate>
{
IBOutlet UISearchBar* mySearchBar;
}
----
- (void)viewDidLoad
{
[mySearchBar setDelegate: self];
mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, self.navigationController.navigationBar.frame.origin.y, 320, 44)];
[self.view addSubview:mySearchBar];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)mySearchBar
{
[mySearchBar resignFirstResponder];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)mySearchBar
{
[mySearchBar resignFirstResponder];
}
答案 0 :(得分:0)
您在分配搜索栏之前设置了委托。尝试之后设置委托。
mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, self.navigationController.navigationBar.frame.origin.y, 320, 44)];
[mySearchBar setDelegate: self];
检查是否首先调用委托方法总是有帮助的。设置断点并查看:)