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

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

一个私有的方法setCenterPlaceholder,在diff和调用这个与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

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

解决方法

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

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

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

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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...