14

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

在此处输入图像描述

在 diff 上有一个私有方法 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 方式”可以做同样的事情。

4

2 回答 2

3

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

_searchBar.placeholder = @"Search                  ";

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

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

<UISearchBarTextField: 0x1349c160; frame = (0 0; 0 0);
于 2014-01-19T23:52:08.677 回答
0

我没有用 a 尝试过,UISearchBar但这适用于 a 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;
}

希望能帮助到你。

于 2014-01-06T19:39:30.710 回答