UISearchBar 的 placeholder 居左展示

0.备注:

本文是参考网上其他文章写的,权作学习记录.

1.新建一个 UISearchBar 的分类

UISearchBar+DJSearchBarPlaceholder

2.代码部分
.h 文件内:

#import 

@interface UISearchBar (DJSearchBarPlaceholder)

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

@end

.m 文件内:

#import "UISearchBar+DJSearchBarPlaceholder.h"

@implementation UISearchBar (DJSearchBarPlaceholder)

-(void)changePlaceholderToLeft:(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

3.使用

初始化 UISearchBar 对象并调用分类里的对象方法设置 placeholder 即可.

你可能感兴趣的:(UISearchBar 的 placeholder 居左展示)