解決方案:建立一個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; 最後在工程中用到UISearchBar的類中匯入#UISearchBar+ZMSearchBarPlaceholder.h標頭檔,