在iOS 7上UISearchBar左对齐占位符文本?

前端之家收集整理的这篇文章主要介绍了在iOS 7上UISearchBar左对齐占位符文本?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在iOS 7 UISearchBar上,占位符文本居中,我想禁用它,并使其始终像以前一样粘在左边.

有一个私有的方法setCenterPlaceholder,在diff和调用这个与BOOL将做出旅程. https://gist.github.com/nscoding/7220368

标题文件

  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. #import "NSCodingSearchBar.h"
  2.  
  3.  
  4. // ------------------------------------------------------------------------------------------
  5.  
  6.  
  7. @implementation NSCodingSearchBar
  8.  
  9.  
  10. // ------------------------------------------------------------------------------------------
  11. #pragma mark - Initializers
  12. // ------------------------------------------------------------------------------------------
  13. - (instancetype)initWithFrame:(CGRect)frame
  14. {
  15. if ((self = [super initWithFrame:frame]))
  16. {
  17. self.hasCentredPlaceholder = YES;
  18. }
  19.  
  20. return self;
  21. }
  22.  
  23.  
  24. // ------------------------------------------------------------------------------------------
  25. #pragma mark - Methods
  26. // ------------------------------------------------------------------------------------------
  27. - (void)setHasCentredPlaceholder:(BOOL)hasCentredPlaceholder
  28. {
  29. _hasCentredPlaceholder = hasCentredPlaceholder;
  30.  
  31. SEL centerSelector = NSSelectorFromString([NSString stringWithFormat:@"%@%@",@"setCenter",@"Placeholder:"]);
  32. if ([self respondsToSelector:centerSelector])
  33. {
  34. NSMethodSignature *signature = [[UISearchBar class] instanceMethodSignatureForSelector:centerSelector];
  35. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
  36. [invocation setTarget:self];
  37. [invocation setSelector:centerSelector];
  38. [invocation setArgument:&_hasCentredPlaceholder atIndex:2];
  39. [invocation invoke];
  40. }
  41.  
  42. }
  43.  
  44.  
  45. @end

我想知道是否有其他的,不是“哈奇的方式”做同样的事情.

解决方法

要在iOS7中保留占位符的左对齐方式,您可以在占位符字符串的末尾添加空格.例如:
  1. _searchBar.placeholder = @"Search ";

请注意,应该为每个搜索栏和每种语言单独完成.

可以尝试在任何语言的文本之后自动计算所需的空格,但是似乎不可能读取searchBar的textField框架的大小

  1. <UISearchBarTextField: 0x1349c160; frame = (0 0; 0 0);

猜你在找的iOS相关文章