@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 調(diào)整位置
if(@available(iOS11.0, *)){
[_searchBar setPositionAdjustment:UIOffsetMake(0,0)forSearchBarIcon:UISearchBarIconSearch];
}
結(jié)束的方法? searchBarTextDidEndEditing:(UISearchBar*)searchBar 判斷是否有內(nèi)容
if(@available(iOS11.0, *)){
if(!_searchBar.text.length) {
[_searchBar setPositionAdjustment:UIOffsetMake((_searchBar.width-_width)/2.0,0) forSearchBarIcon:UISearchBarIconSearch];
}
}