iOS巔峰之如何讓UISearchBar佔位符居左
阿新 • • 發佈:2019-02-02
解決方法:新建一個UISearchBar的category,我這裡新建的名字為UISearchBar+ZMSearchBarPlaceholder
程式碼如下:
UISearchBar+ZMSearchBarPlaceholder.h
#import <UIKit/UIKit.h>
@interface UISearchBar (ZMSearchBarPlaceholder)
-(void)changeLeftPlaceholder:(NSString *)placeholder;
@end
UISearchB ar+ZMSearchBarPlaceholder.h
@implementation UISearchBar (ZMSearchBarPlaceholder)
-(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
然後呼叫該方法即可:
-(void)changeLeftPlaceholder:(NSString *)placeholder;