我有一个视图控制器类,在其xib中我添加了3个实体:容器视图,搜索栏容器视图和按钮。我已经使用故事板上的自动布局约束将搜索栏容器和按钮排列在控制器视图的顶部。它们一起跨越视图的整个宽度并占据等于44px的高度。它们下面是容器视图,其顶部与搜索栏容器视图的底部对齐。以下是viewDidLoad和其他相关方法:
- (void)viewDidLoad
{
[super viewDidLoad];
[self addTableView];
self.searchControllerInternal = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchControllerInternal.delegate = self;
self.searchControllerInternal.searchResultsUpdater = self;
self.searchControllerInternal.dimsBackgroundDuringPresentation = NO;
self.searchControllerInternal.searchBar.delegate = self;
[self addSearchControllerSearchBarToView];
}
-(void)addSearchControllerSearchBarToView
{
UISearchBar *pSearchBar = self.searchControllerInternal.searchBar;
self.searchBarContainerView.translatesAutoresizingMaskIntoConstraints = NO;
[self.searchBarContainerView addSubview:pSearchBar];
pSearchBar.translatesAutoresizingMaskIntoConstraints = NO;
[self addSearchBarConstraints];
}
-(void)addSearchBarConstraints
{
UISearchBar *pSearchBar = self.searchControllerInternal.searchBar;
{
NSLayoutConstraint *pConstraint = [NSLayoutConstraint constraintWithItem:pSearchBar attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual toItem:self.searchBarContainerView
attribute:NSLayoutAttributeTop
multiplier:1
constant:0];
[self.searchBarContainerView addConstraint:pConstraint];
self.searchBarTopConstraint = pConstraint;
}
{
NSLayoutConstraint *pLeadingConstraint = [NSLayoutConstraint constraintWithItem:pSearchBar
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.searchBarContainerView
attribute:NSLayoutAttributeLeft
multiplier:1
constant:0];
[self.searchBarContainerView addConstraint:pLeadingConstraint];
}
{
NSLayoutConstraint *pTrailingConstraint = [NSLayoutConstraint constraintWithItem:pSearchBar
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.searchBarContainerView
attribute:NSLayoutAttributeRight
multiplier:1
constant:0];
[self.searchBarContainerView addConstraint:pTrailingConstraint];
}
{
NSLayoutConstraint *pBottomConstraint = [NSLayoutConstraint constraintWithItem:pSearchBar
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.searchBarContainerView
attribute:NSLayoutAttributeBottom
multiplier:1
constant:0];
[self.searchBarContainerView addConstraint:pBottomConstraint];
}
}
视图正确加载。但是,在点击搜索栏时,搜索栏会移出其容器视图。搜索栏容器视图位于状态栏的下方,搜索栏也应位于该状态栏下方,但它实际上已移出可见区域。为什么会这样?此外,如果dimsBackgroundDuringPresentation设置为TRUE,那么当搜索处于活动状态时,如果用户点击屏幕上的任意位置,应用程序会崩溃,并说"视图层次结构没有为约束做好准备"