0

我在 UINavigationBar 中添加了 UISearchBar 及其显示,但委托方法不起作用。我的代码如下:

主视图控制器.h

@interface MainViewController : UIViewController<UISearchBarDelegate>  {

}

@property(nonatomic, readonly) UISearchBar *_searchBar;
@property(nonatomic, assign) id<UISearchBarDelegate> delegate;

主视图控制器.m

-(void)viewDidLoad  {
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(320.0, 0.0, 320.0, 44.0)];
    _searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc]    
initWithCustomView:_searchBar];
    _searchBar.delegate = self;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText  {
    NSLog(@"textDidChange is firing with %@",searchText);
}

它甚至只显示输入的文本!请给我建议。谢谢!

4

1 回答 1

0

您必须将界面生成器中的搜索栏连接到代码。它必须是一个 IBOutlet。

代码看起来像

@property (strong, nonatomic) IBOutlet UISearchBar *searchBar;

你不需要声明

@property(nonatomic, assign) id<UISearchBarDelegate> delegate;
于 2013-07-15T14:23:13.390 回答