@property(nonatomic,assign)CGFloatwidth;
//判断版本
if(@available(iOS11.0, *)){
UITextField *textField = [self.searchBar valueForKey:@"searchField"];
[textField sizeToFit];
//记录一下这个时候的宽度
_width= textField.frame.size.width;
[_searchBar setPositionAdjustment:UIOffsetMake((_searchBar.width-_width)/2.0,0)forSearchBarIcon:UISearchBarIconSearch];
}
然后在代理方法 searchBarTextDidBeginEditing:(UISearchBar*)searchBar 调整位置
if(@available(iOS11.0, *)){
[_searchBar setPositionAdjustment:UIOffsetMake(0,0)forSearchBarIcon:UISearchBarIconSearch];
}
结束的方法 searchBarTextDidEndEditing:(UISearchBar*)searchBar 判断是否有内容
if(@available(iOS11.0, *)){
if(!_searchBar.text.length) {
[_searchBar setPositionAdjustment:UIOffsetMake((_searchBar.width-_width)/2.0,0) forSearchBarIcon:UISearchBarIconSearch];
}
}
网友评论