简体   繁体   中英

Placeholder text misaligned in UITextField of UISearchBar

I'm trying to customize UISearchBar's font through appearance proxy. It works, but somehow, the placeholder text is not centered vertically. I tried to set the vertical alignment property; the placeholder text would get centred but text entered would be slightly below the center line... Is there any way to fix this?

Edit: Code I used to add custom font:

[[UITextField appearanceWhenContainedIn: [UISearchBar class], nil]
                                setFont: [UIFont customFontWithSize: 17]];

占位符文本

普通文字

Whenever this happens to me, it is usually caused by some modification to UIAppearance not blending well with UISearchBar . Look at any previous hacks you may have made and perhaps try commenting them out one at a time.

In my particular case it was actually a modification to NSForegroundColor in a text attribute, so this misalignment may be unrelated to your font change.

You need to set alignment of textField inside the searchBar. Get textField from subviews of UISearch bar and simply set its alignment to center.Try sample code below.

- (void)viewDidLoad
{
    for (UITextField *txt in _searchbar.subviews) {
        if ([txt isKindOfClass:[UITextField class]]) {
            [txt setTextAlignment:NSTextAlignmentCenter];
        }
    }
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

here _searchbar is outlet of UISearchBar.

- (void)viewDidLoad
{

    for (UITextField *txt in search.subviews) {
        if ([txt isKindOfClass:[UITextField class]]) {
            txt.font = [UIFont fontWithName:@"Arial-BoldMT" size:17];
            txt.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
        }
    }

    [super viewDidLoad];

}

Try this code once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM