On iOS 7 UISearchBar the placeholder text is centred and I want to disable that and make it always stick to the left like it was before.
There is a private method setCenterPlaceholder, on the diffs and calling this with a BOOL will make the trip. https://gist.github.com/nscoding/7220368
Header file
@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
Implementation file
#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
I am wondering if there is any other, not "Hacky way" that does the same thing.
I haven't tried it with a
UISearchBar
but this works with aUITextField
. I Subclassed it and overrodeleftViewRectForBounds:
,textRectForBounds:
andeditingRectForBounds:
, here is the code:Hope it helps.
To get left alignment of the placeholder in iOS7 you can add white spaces to the end of your placeholder string. For example:
Note that it is should be done separately for each search bar and each language.
One could try to write automatic calculation of needed spaces after text for any language but it seems impossible to read the size of searchBar's textField frame