项目经验实用小功能傲视苍穹iOS《Objective-C》VIP专题

iOS中更改UISearchBar占位符居左

2016-10-20  本文已影响2050人  90后的晨仔
#特别声明博客来源地址: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:&centeredPlaceholder atIndex:2];
        [invocation invoke];
    }
}
@end

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

然后调用该方法即可:

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

demo的下载地址如下:  

https://github.com/624990742/GestureSummary

上一篇下一篇

猜你喜欢

热点阅读