1. 程式人生 > >iOS巔峰之如何讓UISearchBar佔位符居左

iOS巔峰之如何讓UISearchBar佔位符居左

解決方法:新建一個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:&centeredPlaceholder atIndex:2
]; [invocation invoke]; } } @end

然後呼叫該方法即可:

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

最後在工程中用到UISearchBar的類中匯入#UISearchBar+ZMSearchBarPlaceholder.h標頭檔案,