2013-10-29 48 views
14

在iOS 7 UISearchBar佔位符文本居中,我想禁用它,並使它始終像以前一樣粘到左邊。在iOS 7上,UISearchBar左對齊佔位符文本?

enter image description here

有一個私有方法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 

我想知道是否有任何其他的,而不是做同樣的事情 「哈克的方式」。

+0

如果您在該問題的代碼是更好,而不是隻是連接到它。 –

+0

你試過這個嗎? http://stackoverflow.com/a/19555305/2155985 –

+0

我不認爲這是一個好主意。你應該儘可能地堅持標準。 – anders

回答

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; 
} 

希望它能幫助。

3

要在iOS7中佔位符的左對齊,您可以在佔位符字符串的末尾添加空格。例如:

_searchBar.placeholder = @"Search     "; 

請注意,它應該針對每個搜索欄和每種語言分別進行。

一個可以嘗試的文字爲任何語言後寫所需空間的自動計算,但它似乎是不可能的閱讀搜索欄的文本框框架的尺寸

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

有什麼不對?它確實有效,只是可能看起來很愚蠢。 – malex

+0

我用這個我的自我。現在,如何添加這些空白? –

+0

您可以在h和之前輸入上例中的普通空格「 或者您可以將不同空格的utf-8編碼寫爲\ uXXXX – malex