Hacky way 解决 iOS 7 UISearchBar 默认文本居左展示问题

参考:ON IOS 7 UISEARCHBAR LEFT ALIGN PLACEHOLDER TEXT?

控件代码:https://gist.github.com/CoCrash/de56f5f0b70b7eb6d6e3

 

一个私有方法setCenterPlaceholder,在调用时修改这个布尔值可以实现修改位置的效果。

1 @interface NSCodingSearchBar : UISearchBar

2  

3 // Default by the system is YES.

4 // https://github.com/nst/iOS-Runtime-Headers/blob/master/Frameworks/UIKit.framework/UISearchBar.h

5 @property (nonatomic, assign, setter = setHasCentredPlaceholder:) BOOL hasCentredPlaceholder;

6  

7 @end

实现文件:

 1 @implementation NSCodingSearchBar

 2  

 3  

 4 // ------------------------------------------------------------------------------------------

 5 #pragma mark - Initializers

 6 // ------------------------------------------------------------------------------------------

 7 - (instancetype)initWithFrame:(CGRect)frame

 8 {

 9     if ((self = [super initWithFrame:frame]))

10     {

11         self.hasCentredPlaceholder = YES;

12     }

13     

14     return self;

15 }

16  

17  

18 // ------------------------------------------------------------------------------------------

19 #pragma mark - Methods

20 // ------------------------------------------------------------------------------------------

21 - (void)setHasCentredPlaceholder:(BOOL)hasCentredPlaceholder

22 {

23     _hasCentredPlaceholder = hasCentredPlaceholder;

24     

25     SEL centerSelector = NSSelectorFromString([NSString stringWithFormat:@"%@%@", @"setCenter", @"Placeholder:"]);

26     if ([self respondsToSelector:centerSelector])

27     {

28         NSMethodSignature *signature = [[UISearchBar class] instanceMethodSignatureForSelector:centerSelector];

29         NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];

30         [invocation setTarget:self];

31         [invocation setSelector:centerSelector];

32         [invocation setArgument:&_hasCentredPlaceholder atIndex:2];

33         [invocation invoke];

34     }

35     

36 }

37  

38  

39 @end

 

你可能感兴趣的:(search)