如何以编程方式在UITableViewController的导航栏中设置UISearchDisplayBar

时间:2013-10-03 00:26:11

标签: ios objective-c uitableview uisearchbar

我目前有一个表视图控制器,并在界面构建器内的我的表视图控制器的顶部或上方放置了一个UISearchDisplayController。在我的实现文件的viewDidLoad中,我继续将搜索栏分配给navigationItem.titleView。我现在的问题是第一个表视图单元格中有更多的空间,因为它仍然认为searchdisplaycontroller在那里。你可以在这里看到它:http://imgur.com/u6cQew2

这是代码:

.h文件

@interface searchTableViewController : UITableViewController <UISearchBarDelegate>
{
    UISearchBar *searchDrugBar;
}
@property (nonatomic, strong) IBOutlet UISearchBar *searchDrugBar;

.m文件

- (void)viewDidLoad
{
    [super viewDidLoad];
    searchDrugBar.placeholder = @"Search for info";

    self.navigationItem.titleView = self.searchDisplayController.searchBar;
    [self.searchDisplayController setActive: YES animated: YES];
    [self.searchDisplayController.searchBar becomeFirstResponder];

}

有任何建议或想法吗?提前谢谢!

2 个答案:

答案 0 :(得分:1)

尝试以编程方式创建searchBar,除非您有自己的理由,否则我在故事板中创建它没有任何附加价值。

首先从故事板中删除它:

- (void)viewDidLoad
{
    [super viewDidLoad];

    searchDrugBar = [[UISearchBar alloc] init];
    searchDrugBar.frame = CGRectMake(0, 0, 200,44); // it could be unnecessary
    searchDrugBar.delegate = self;
    searchDrugBar.placeholder = @"Search for info";

    self.navigationItem.titleView = self.searchDisplayController.searchBar;
    [self.searchDisplayController setActive: YES animated: YES];
    [self.searchDisplayController.searchBar becomeFirstResponder];

}

答案 1 :(得分:0)

self.navigationItem.titleView = self.searchBarTop;

=&GT;至左/右搜索栏: -

UIBarButtonItem *searchBarItem = [[UIBarButtonItem alloc] initWithCustomView:searchBar];

self.navigationItem.rightBarButtonItem = searchBarItem;

- (void)viewDidLoad
{
    ...
    self.searchDisplayController.displaysSearchBarInNavigationBar = true;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem new];
    ...
}

==&GT;在这里给出更多参考它可能是有用的我希望它对你有用..

How to animate add UISearchBar on top of UINavigationBar