iOS 设置系统 SearchBar logo 和 placeholder 居左

Posted by Calvin on 2017-04-06

我们在开发时使用系统的SearchBar时,搜索的logo和placeholder都是默认距中的,但是有些产品需要搜索框的搜索logo和placeholder从左侧开始展示,现在就这个小需求进行一下实现。

1、首先创建一个UISearchBarcategory,命名为Placeholder。创建成功后会出现UISearchBar+Placeholder.hUISearchBar+Placeholder.m文件

2、在UISearchBar+Placeholder.h文件中添加-(void)changeLeftPlaceholder:(NSString *)placeholder;,在UISearchBar+Placeholder.m文件中进行实现,代码如下:

-(void)changeLeftPlaceholder:(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:&centeredPlaceholder atIndex:2];
[invocation invoke];
}
}

3、调用。

在需要使用SearchBar logo和Placeholder居左的类中导入头文件UISearchBar+Placeholder.h

示例如下:

UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(90, 20, ScreenWidth-100, 40)];
searchBar.delegate = self;
[searchBar changeLeftPlaceholder:@"搜索你想看的文章"];
searchBar.barTintColor = [UIColor redColor];
searchBar.tintColor = [UIColor redColor];
searchBar.backgroundImage = [UIImage new];
[naviView addSubview:searchBar];

4、最终效果:

20170406149147948075107.png