我以编程方式创建了UISearchController
,并为我添加的searchBar设置了框架。但searchBar
有wider frame
,点击它后点按带有搜索栏的cancel
按钮;它重新获得了正确的框架。如何在viewDidLoad
设置正确的内容?
代码就是这样:
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 310, 44)];
searchControllerMain = [[UISearchController alloc] initWithSearchResultsController:self.searchResultController];
searchControllerMain.searchBar.delegate = self;
searchControllerMain.searchResultsUpdater = self;
[searchControllerMain.searchBar sizeToFit];
[searchControllerMain.searchBar setPlaceholder:@"events"];
searchControllerMain.searchBar.barTintColor = [UIColor clearColor];
searchControllerMain.searchBar.searchBarStyle = UISearchBarStyleMinimal;
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor lightGrayColor]];
[self.searchResultController.tableView reloadData];
UIView *searchBarContainer = [[UIView alloc] initWithFrame:searchBar.frame];
[searchBarContainer addSubview:searchControllerMain.searchBar];
self.navigationItem.rightBarButtonItem= [[UIBarButtonItem alloc] initWithCustomView:searchBarContainer];
答案 0 :(得分:0)
以下是我如何在导航项searchBar
中放置titleView
。
self.searchBar = [UISearchBar new];
self.searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.searchBar.searchBarStyle = UISearchBarStyleMinimal;
self.searchBar.placeholder = @"Search gospel events";
self.searchBar.delegate = self;
self.navigationItem.titleView = self.searchBar;
如您所见,我没有设置框架。它以正确的初始尺寸开始,并随着方向的变化调整尺寸。
您是否尝试过设置明确的autoresizingMask
?我从未尝试将其放在自定义栏按钮项中,因此我不确定这是否也会解决您的自定义容器问题。
答案 1 :(得分:0)
试试这个:
-(void)viewDidLayoutSubviews{
[super viewDidLayoutSubviews];
[searchControllerMain.searchBar setFrame:CGRectMake(0, 0, 310, 44)];
[searchControllerMain.searchBar setBounds:CGRectMake(0, 0, 310, 44)];
}
它对我有用!!