I did one UISearchBar extension & category for customize text filed within search bar.
Compatible from iOS 9 to iOS 13.
Swift 4+
import UIKit
extension UISearchBar {
// Due to searchTextField property who available iOS 13 only, extend this property for iOS 13 previous version compatibility
var compatibleSearchTextField: UITextField {
guard #available(iOS 13.0, *) else { return legacySearchField }
return self.searchTextField
}
private var legacySearchField: UITextField {
if let textField = self.subviews.first?.subviews.last as? UITextField {
// Xcode 11 previous environment
return textField
} else if let textField = self.value(forKey: "searchField") as? UITextField {
// Xcode 11 run in iOS 13 previous devices
return textField
} else {
// exception condition or error handler in here
return UITextField()
}
}
}
Usage Example:
var searchController: UISearchController?
searchController?.searchBar.compatibleSearchTextField.textColor = UIColor.XXX
searchController?.searchBar.compatibleSearchTextField.backgroundColor = UIColor.XXX
Objective-C
UISearchBar+SearchTextField.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UISearchBar (SearchTextField)
// Due to searchTextField property who available iOS 13 only, extend this property for iOS 13 previous version compatibility
@property (nonatomic, readonly) UITextField *compatibleSearchTextField;
@end
NS_ASSUME_NONNULL_END
UISearchBar+SearchTextField.m
#import "UISearchBar+SearchTextField.h"
@implementation UISearchBar (SearchTextField)
- (UITextField *)compatibleSearchTextField {
if (@available(iOS 13.0, *)) {
#ifdef __IPHONE_13_0
return self.searchTextField;
#else
// Xcode 11 run in iOS 13 previous devices
return (UITextField *)[self valueForKey:@"searchField"];
#endif
} else {
// Xcode 11 previous environment
return [[[self.subviews firstObject] subviews] lastObject];
}
}
@end
Usage Example:
- (UISearchBar *)searchBar {
if (!_searchBar) {
_searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(X, X, X, X)];
_searchBar.compatibleSearchTextField.textColor = [UIColor XXX];
_searchBar.compatibleSearchTextField.backgroundColor = [UIColor XXX];
}
return _searchBar
}
barTintColor
property that you tried above. Make sure to setisTranslucent
tofalse
in code or storyboard. – Runoff