0.備注:
本文是參考網(wǎng)上其他文章寫的,權(quán)作學(xué)習(xí)記錄.
1.新建一個 UISearchBar 的分類
UISearchBar+DJSearchBarPlaceholder
2.代碼部分
.h 文件內(nèi):
#import <UIKit/UIKit.h>
@interface UISearchBar (DJSearchBarPlaceholder)
-(void)changePlaceholderToLeft:(NSString *)placeholder;
@end
.m 文件內(nèi):
#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 對象并調(diào)用分類里的對象方法設(shè)置 placeholder 即可.