#特别声明博客来源地址:http://cathra.github.io/2016/03/17/UISearchBar-Placeholder-Left-align/
小白的我只是代码的搬运工🙂,
UISearchBar的占位符 (Placeholder) 如何居左显示 ?
做项目的时候遇到这个问题,虽然不是什么比较大的知识点,但是我觉着应该会有朋友纠结这个问题,所以这里就把自己查到的结果分享一下。
解决方法:新建一个UISearchBar的category,我这里新建的名字为
UISearchBar+JCSearchBarPlaceholder
代码如下:
UISearchBar+JCSearchBarPlaceholder.h
#import <UIKit/UIKit.h>
@interface UISearchBar (JCSearchBarPlaceholder)
-(void)changeLeftPlaceholder:(NSString *)placeholder;
@end
UISearchBar+JCSearchBarPlaceholder.h
@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:¢eredPlaceholder atIndex:2];
[invocation invoke];
}
}
@end
最后在工程中用到UISearchBar的类中导入#UISearchBar+JCSearchBarPlaceholder.h
头文件,
然后调用该方法即可:
-(void)changeLeftPlaceholder:(NSString *)placeholder;
demo的下载地址如下:
网友评论