ios实现UISearchBar的Placeholder居左显示

释放双眼,带上耳机,听听看~!

UISearchBar的占位符 (Placeholder) 如何居左显示 ?

做项目的时候遇到这个问题,虽然不是什么比较大的知识点,但是我觉着应该会有朋友纠结这个问题,所以这里就把自己查到的结果分享一下。

从ios7开始,ios系统UISearchBar组件显示Placeholder图标提示信息和放大镜都是居中的,而且没有相应的方法、属性对placeholder进行操作。本文提供一个UISearchBar的扩展,使placeholder的内容居左

UISearchBar+Extension.h

#import <UIKit/UIKit.h>
@interface UISearchBar(Extension)
-(void)setLeftPlaceholder:(NSString *)placeholder;
@end

 

UISearchBar+Extension.m

@implementation UISearchBar (JCSearchBarPlaceholder)
-(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];
}
}
@end

最后在工程中用到UISearchBar的类中导入#UISearchBar+JCSearchBarPlaceholder.h头文件,

然后调用该方法即可:

-(void)changeLeftPlaceholder:(NSString *)placeholder;

 

 

人已赞赏
iOS文章

iOS statusbar 状态栏 跟随navigationbar的颜色而改变

2020-3-30 2:33:02

iOS文章

IOS [__NSCFConstantString size]: unrecognized selector sent to instance 错误

2020-3-30 3:48:55

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索