在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方式”做同样的事情。
答案 0 :(得分:3)
要在iOS7中左对齐占位符,可以在占位符字符串的末尾添加空格。例如:
_searchBar.placeholder = @"Search ";
请注意,应该为每个搜索栏和每种语言单独完成。
可以尝试在任何语言的文本之后编写所需空格的自动计算,但似乎无法读取searchBar的textField框架的大小
<UISearchBarTextField: 0x1349c160; frame = (0 0; 0 0);
答案 1 :(得分:0)
我没有尝试使用UISearchBar
,但这适用于UITextField
。我对其进行了分类并覆盖了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;
}
希望它有所帮助。