最近手機(jī)更新了iOS11系統(tǒng),把項(xiàng)目在手機(jī)上運(yùn)行之后發(fā)現(xiàn)原來正常大小的searchBar高度明顯增加了鳍怨,放在導(dǎo)航欄上更為明顯齿穗。就想著要把searchBar的高度改一下涉波,在網(wǎng)上搜了一下全都一樣客扎,而且還是用swift寫的祟峦,所以就想著按照那個(gè)方法寫一個(gè)OC版本的(參考文章地址:www.cnblogs.com/theDesertIslandOutOfTheWorld/p/5015653.html)。
iOS11系統(tǒng)的searchBar
iOS10.3系統(tǒng)的searchBar
具體的UISearchBar的中子控件及其布局可以參考原文章的分析徙鱼,現(xiàn)在直接上代碼
新建UISearchBar的子類宅楞,增加成員屬性contentInset,用來調(diào)整UISearchBarTextField距離父控件的邊距。contentInset的setter方法
#pragma mark - setter method
- (void)setContentInset:(UIEdgeInsets)contentInset {
_contentInset.top = contentInset.top;
_contentInset.bottom = contentInset.bottom;
_contentInset.left = contentInset.left;
_contentInset.right = contentInset.right;
self.isChangeFrame = YES;
[self layoutSubviews];
}
- (void)layoutSubviews {
[super layoutSubviews];
for (UIView *subView in self.subviews[0].subviews) {
if ([subView isKindOfClass:[UIImageView class]]) {
//移除UISearchBarBackground
[subView removeFromSuperview];
}
if ([subView isKindOfClass:[UITextField class]]) {
CGFloat height = self.bounds.size.height;
CGFloat width = self.bounds.size.width;
if (_isChangeFrame) {
//說明contentInset已經(jīng)被賦值
// 根據(jù)contentInset改變UISearchBarTextField的布局
subView.frame = CGRectMake(_contentInset.left, _contentInset.top, width - 2 * _contentInset.left, height - 2 * _contentInset.top);
} else {
// contentSet未被賦值
// 設(shè)置UISearchBar中UISearchBarTextField的默認(rèn)邊距
CGFloat top = (height - 28.0) / 2.0;
CGFloat bottom = top;
CGFloat left = 8.0;
CGFloat right = left;
_contentInset = UIEdgeInsetsMake(top, left, bottom, right);
}
}
}
}
使用
- (MySelfSearchBar *)addSearchBarWithFrame:(CGRect)frame {
self.definesPresentationContext = YES;
MySelfSearchBar *searchBar = [[MySelfSearchBar alloc]initWithFrame:frame];
searchBar.delegate = self;
searchBar.searchBarStyle = UISearchBarStyleDefault;
searchBar.placeholder = @"查詢";
[searchBar setShowsCancelButton:NO];
[searchBar setTintColor:KGenericColor];
if (self.isChangeSearchBarFrame || IS_IOS_11) {
CGFloat height = searchBar.bounds.size.height;
CGFloat top = (height - 20.0) / 2.0;
CGFloat bottom = top;
searchBar.contentInset = UIEdgeInsetsMake(top, 0, bottom, 0);
}
return searchBar;
}
加載到導(dǎo)航欄上
MySelfSearchBar *searchBar = [self addSearchBarWithFrame:CGRectMake(0, 0, kScreenWidth - 2 * 44 - 2 * 15, 44)];
UIView *wrapView = [[UIView alloc] initWithFrame:searchBar.frame];
[wrapView addSubview:searchBar];
self.navigationItem.titleView = wrapView;
通過新增屬性contentInset來改變searchBar的高度
運(yùn)行結(jié)果
改變與父控件的邊距后效果
demo地址:https://github.com/DreamTravelingLight/searchBarDemo.git
以前的源碼沒了厌衙,就簡單的寫了一下距淫,明白了原理可以根據(jù)自己的項(xiàng)目再寫一個(gè)