【OC】适配iOS11.0 UISearchBar placeholder 不居中显示的问题

实现方法,自定义UISearchBar//  placeholder 和icon 和 间隙的整体宽度
// @property (nonatomic, assign) CGFloat placeholderWidth;

//  在layoutSubviews里默认先居中
if (@available(iOS 11.0, *)) {
        [self setPositionAdjustment:UIOffsetMake((field.frame.size.width-self.placeholderWidth)/2, 0) forSearchBarIcon:UISearchBarIconSearch];
 } 

// 实现textfield的代理方法
// 开始编辑的时候重置为靠左
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
// 继续传递代理方法
     if ([self.delegate respondsToSelector:@selector(searchBarShouldBeginEditing:)]) {
        [self.delegate searchBarShouldBeginEditing:self];
    }
    if (@available(iOS 11.0, *)) {
        [self setPositionAdjustment:UIOffsetZero forSearchBarIcon:UISearchBarIconSearch];
    }
    return YES;
}

// 结束编辑的时候设置为居中
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField {
     if ([self.delegate respondsToSelector:@selector(searchBarShouldEndEditing:)]     {
        [self.delegate searchBarShouldEndEditing:self];
    }
    if (@available(iOS 11.0, *)) {
        [self setPositionAdjustment:UIOffsetMake((textField.frame.size.width-self.placeholderWidth)/2, 0) forSearchBarIcon:UISearchBarIconSearch];
    }
    return YES;
}

你可能感兴趣的:(【OC】适配iOS11.0 UISearchBar placeholder 不居中显示的问题)