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

在iOS 7 UISearchBar上,占位符文本居中,我想禁用它并使它始终像以前一样粘在左边。

在此处输入图像描述

在diffs上有一个私有方法setCenterPlaceholder,并且用BOOL调用它将使这个行程。 https://gist.github.com/nscoding/7220368

头文件

@interface NSCodingSearchBar : UISearchBar // Default by the system is YES. // https://github.com/nst/iOS-Runtime-Headers/blob/master/Frameworks/UIKit.framework/UISearchBar.h @property (nonatomic, assign, setter = setHasCentredPlaceholder:) BOOL hasCentredPlaceholder; @end 

实施文件

 #import "NSCodingSearchBar.h" // ------------------------------------------------------------------------------------------ @implementation NSCodingSearchBar // ------------------------------------------------------------------------------------------ #pragma mark - Initializers // ------------------------------------------------------------------------------------------ - (instancetype)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.hasCentredPlaceholder = YES; } return self; } // ------------------------------------------------------------------------------------------ #pragma mark - Methods // ------------------------------------------------------------------------------------------ - (void)setHasCentredPlaceholder:(BOOL)hasCentredPlaceholder { _hasCentredPlaceholder = hasCentredPlaceholder; SEL centerSelector = NSSelectorFromString([NSString stringWithFormat:@"%@%@", @"setCenter", @"Placeholder:"]); if ([self respondsToSelector:centerSelector]) { NSMethodSignature *signature = [[UISearchBar class] instanceMethodSignatureForSelector:centerSelector]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; [invocation setTarget:self]; [invocation setSelector:centerSelector]; [invocation setArgument:&_hasCentredPlaceholder atIndex:2]; [invocation invoke]; } } @end 

我想知道是否有任何其他的,而不是“Hacky方式”做同样的事情。

要在iOS7中左对齐占位符,可以在占位符字符串的末尾添加空格。 例如:

 _searchBar.placeholder = @"Search "; 

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

可以尝试在任何语言的文本之后编写所需空间的自动计算,但似乎无法读取searchBar的textField框架的大小

  

我没有尝试使用UISearchBar但这适用于UITextField 。 我对它进行了Subclassed并覆盖了leftViewRectForBounds:textRectForBounds:editingRectForBounds: ,这里是代码:

 - (CGRect)textRectForBounds:(CGRect)bounds { CGRect inset = CGRectMake(bounds.origin.x + kLeftTextPadding, bounds.origin.y, bounds.size.width - kLeftTextPadding, bounds.size.height); return inset; } 

希望能帮助到你。