Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios 13 - Custom SearchBar with UISearchBar _searchField not working

Before Xcode-11-Beta (ios13) below code for custom searchbar value for key to get textField working fine. Now getting below crash log.

'NSGenericException', reason: 'Access to UISearchBar's _searchField ivar is prohibited. This is an application bug'

- (UITextField *)textField
{
 return [self valueForKey:@"_searchField"];
}

Any help appreciated.

like image 291
Pratik Sodha Avatar asked Jun 19 '19 12:06

Pratik Sodha


3 Answers

The SDK now provides UISearchBar.searchTextField so you can simply replace your private API implementation with the public API.

searchBar.searchTextField.backgroundColor = [UIColor blueColor];
like image 192
Jordan H Avatar answered Nov 07 '22 18:11

Jordan H


If we want to support iOS 12 and earlier also while compiling with Xcode 11, then we can make an extension of UISearchBar where we can grab the textfield

extension UISearchBar {

    var textField : UITextField? {
        if #available(iOS 13.0, *) {
            return self.searchTextField
        } else { // Fallback on earlier versions
            for subview in subviews.first?.subviews ?? [] {
                if let textField = subview as? UITextField {
                    return textField
                }
            }
        }
        return nil
    }
}

USAGE

searchBar.textField?.font = UIFont.systemFont(ofSize: 15.0)

Here we can access all textField's properties and modify as per our needs in UISearchBar

There is a change in the view hierarchy. So by printing self.subviews[0]).subviews where self in UISearchBar


For iOS 12 and earlier

enter image description here

For iOS 13+

enter image description here

Along with UISearchBarBackground, now we have UISearchBarSearchContainerView and UISearchBarScopeContainerView whereas UISearchBarTextField is missing which is replaced by an extension provided by Apple in UISearchTextField class

extension UISearchBar {

    
    open var searchTextField: UISearchTextField { get }
}

So we can directly access searchBar.searchTextField in iOS 13 and above devices whereas it will lead to a crash if we try to access this property in iOS 12 and below OS devices.

The crash will be like this:

[UISearchBar searchTextField]: unrecognized selector sent to instance

enter image description here

Here is the Apple doc for this

like image 38
Rajan Maheshwari Avatar answered Nov 07 '22 16:11

Rajan Maheshwari


I had the same crash, with IOS 13 you don't need anymore the .value(forKey:)

Here is the line that caused the crash:

if let searchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField {

And this was the fix:

let searchField = searchController.searchBar.searchTextField
like image 26
Daniel Ardeleanu Avatar answered Nov 07 '22 16:11

Daniel Ardeleanu