我们在开发时使用系统的SearchBar时,搜索的logo和placeholder都是默认距中的,但是有些产品需要搜索框的搜索logo和placeholder从左侧开始展示,现在就这个小需求进行一下实现。
1、首先创建一个UISearchBar
的category
,命名为Placeholder
。创建成功后会出现UISearchBar+Placeholder.h
和UISearchBar+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:¢eredPlaceholder 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、最终效果:
微信扫一扫,向我赞赏
支付宝扫一扫,向我赞赏