UISearchBar的占位符 (Placeholder,包括图片文字) 如何居左显示 ?

转载至:https://blog.csdn.net/qq_33226881/article/details/76512656

UISearchBar的占位符 (Placeholder) 如何居左显示 ?
做项目的时候遇到这个问题,虽然不是什么比较大的知识点,但是我觉着应该会有朋友纠结这个问题,所以这里就把自己查到的结果分享一下。

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

UISearchBar+Extension.h

#import 
    
@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:¢eredPlaceholder atIndex:2];
        [invocation invoke];
    }
}
@end

最后在工程中用到UISearchBar的类中导入#UISearchBar+JCSearchBarPlaceholder.h头文件,
然后调用该方法即可:
-(void)changeLeftPlaceholder:(NSString *)placeholder;

你可能感兴趣的:(UITextview,UITextField,键盘)