我正在创建一个UI组件,该组件应在下面显示一个UILabel
和一个UISearchBar
。
但是,我无法对齐它们,UISearchBar
总是在左右两侧都有多余的空间(红色突出显示)。
我试图通过布局锚直接设置searchBarTextField
的尺寸,但是没有用。
我希望尽可能使用布局锚。
SearchBar.m
:
-(id) init {
self.titleLabel = [UILabel new];
self.searchBar = self.searchController.searchBar;
UIView *searchBarWrapper = [UIView new];
[self.view addSubview:self.titleLabel];
[self.view addSubview:searchBarWrapper];
[searchBarWrapper addSubview:self.searchBar];
[self.titleLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[searchBarWrapper setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.searchBar setTranslatesAutoresizingMaskIntoConstraints:NO];
//[self.titleLabel.widthAnchor constraintEqualToAnchor:self.view.widthAnchor multiplier:1.0].active = YES;
[self.titleLabel.heightAnchor constraintEqualToConstant:14.0].active = YES;
[self.titleLabel.topAnchor constraintEqualToAnchor:self.view.topAnchor].active = YES;
[self.titleLabel.leftAnchor constraintEqualToAnchor:self.view.leftAnchor].active = YES;
[self.titleLabel.rightAnchor constraintEqualToAnchor:self.view.rightAnchor].active = YES;
//[self.titleLabel.bottomAnchor constraintEqualToAnchor:searchBarTextField.topAnchor].active = YES;
[searchBarWrapper.widthAnchor constraintEqualToAnchor:self.view.widthAnchor multiplier:1.0].active = YES;
//[self.searchBar.heightAnchor constraintEqualToConstant:36.0].active = YES;
[searchBarWrapper.topAnchor constraintEqualToAnchor:self.titleLabel.bottomAnchor].active = YES;
[searchBarWrapper.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor].active = YES;
[searchBarWrapper.leftAnchor constraintEqualToAnchor:self.view.leftAnchor].active = YES;
[searchBarWrapper.rightAnchor constraintEqualToAnchor:self.view.rightAnchor].active = YES;
[self.searchBar.topAnchor constraintEqualToAnchor:searchBarWrapper.topAnchor].active = YES;
[self.searchBar.bottomAnchor constraintEqualToAnchor:searchBarWrapper.bottomAnchor].active = YES;
[self.searchBar.leftAnchor constraintEqualToAnchor:searchBarWrapper.leftAnchor].active = YES;
[self.searchBar.rightAnchor constraintEqualToAnchor:searchBarWrapper.rightAnchor constant:16.0].active = YES;
return self;
}
UISearchBarTextField
嵌入了我无法访问的UIView
中。
约束:
@BenOng的方法-可以正常工作,但在第一次点击后会中断:
答案 0 :(得分:0)
UISearchBar具有此属性searchFieldBackgroundPositionAdjustment:UIOffset
,您可以将其设置为UIOffsetMake(-8,0)
,以使文本字段的左侧与搜索栏的左侧对齐。
在完整的搜索栏应位于的位置创建一个UIView,并使搜索栏成为子视图。将搜索栏的右边缘设置在其超级视图之外,直到其右边缘与超级视图对齐为止,它应该多出16个点。确保超级视图的属性clipsToBounds
设置为true,搜索栏背景的多余16点将被裁剪。