不说了,直接上代码
1、解决居左的问题,创建UISearchBar的category类,添加下面的方法
-(void)setLeftPlaceholder:(NSString *)placeholder {
self.placeholder = placeholder;
SEL centerSelector = NSSelectorFromString([NSString stringWithFormat:@"%@%@", @"setCenter", @"Placeholder:"]);
if ([self respondsToSelector:centerSelector]) {
BOOL centeredPlaceholder = NO;
NSMethodSignature *signature = [[UISearchBar class] instanceMethodSignatureForSelector:centerSelector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:self];
[invocation setSelector:centerSelector];
[invocation setArgument:¢eredPlaceholder atIndex:2];
[invocation invoke];
}
}
2、输入框的文字颜色、字体、文本偏移问题
UIFont *font = xxxx // 字体
/* 这种不行,不知道为什么
CGFloat imageHeight = iconImage.size.height; // 14
CGFloat lineHeight = font.lineHeight; // 16.391999999999999
CGFloat offset = (imageHeight-lineHeight)/2.0; // -1.1959999999999997
*/
CGFloat offset = -0.7;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:placeHolder
attributes:@{
NSForegroundColorAttributeName: 颜色值,
NSFontAttributeName : font,
NSBaselineOffsetAttributeName : @(offset),
}];
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setAttributedPlaceholder:attributedString];
3、设置图标
UIImage *iconImage = [UIImage imageNamed:@"index_icon_search"];
[_searchBar setImage:iconImage forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];