Wrong placement of search text field inside search bar on iOS 11

Viewed 3091

I am using UISearchController as part of navigation bar using the new APIs introduced in iOS 11. I am using it in the following manner in my ViewController's viewDidLoad

- (void)viewDidLoad {  
    [super viewDidLoad];  
    [_table setDataSource:self];  
    [_table setDelegate:self];  
    searchController = [[UISearchController alloc] initWithSearchResultsController:nil];  
    [self.navigationItem setSearchController:searchController];  
    [self.navigationItem setHidesSearchBarWhenScrolling:NO];  
    [searchController.searchBar setBackgroundColor:[UIColor greenColor]];  
} 

However, the search text field is rendered at the wrong position inside the search bar. Look at the following screenshot.

https://imgur.com/a/Igf49

I inspected the view hierarchy and found that UISearchBarTextField object (which is not accessible directly to devs) in the search bar has a frame.y value of 1 which is probably causing this issue. I have tested this on iOS 11 beta 10 and iOS 11 GM.

Is this a known issue? Is there any fix for this? Or is it something I am doing wrong on my end?

Any help will be appreciated (:

2 Answers

Here's code which shows how to change the background colour of textField in searchBar on iOS 11.

Before: Default state of iOS 11 searchBar

After: enter image description here

Obj-C: in (void)viewDidLoad use this code:

 if (@available(iOS 11, *)) {
    UITextField *textField = [self.searchController.searchBar valueForKey:@"searchField"];
    UIView *backgroundView = textField.subviews.firstObject;
    backgroundView.backgroundColor = UIColor.whiteColor;
    backgroundView.layer.cornerRadius = 10;
    backgroundView.clipsToBounds = YES;
}

Swift: in viewDidLoad() use this code:

if #available(iOS 11.0, *) {
    if let textfield = scb.value(forKey: "searchField") as? UITextField {
        textfield.textColor = UIColor.blue

        if let backgroundview = textfield.subviews.first {
            backgroundview.backgroundColor = UIColor.white
            backgroundview.layer.cornerRadius = 10;
            backgroundview.clipsToBounds = true;
        }
    }
}
Related