Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On iOS 7 UISearchBar left align placeholder text?

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.

enter image description here

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.

like image 536
nscoding Avatar asked Oct 29 '13 18:10

nscoding


1 Answers

To get left alignment of the placeholder in iOS7 you can add white spaces to the end of your placeholder string. For example:

_searchBar.placeholder = @"Search                  ";

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

<UISearchBarTextField: 0x1349c160; frame = (0 0; 0 0);
like image 106
malex Avatar answered Nov 01 '22 19:11

malex