Skip to content

Instantly share code, notes, and snippets.

@joshua24322
Last active September 24, 2019 18:16
Show Gist options
  • Save joshua24322/3e02d014c3ce824ae943f446ae1f79e1 to your computer and use it in GitHub Desktop.
Save joshua24322/3e02d014c3ce824ae943f446ae1f79e1 to your computer and use it in GitHub Desktop.
UISearchBar category and extension for conveniently customize the text fields within search bar. Via test confirm, compatible from iOS 9 to iOS 13
//
// UISearchBar+Extension.swift
//
import UIKit
extension UISearchBar {
var dtXcode: Int {
if let dtXcodeString = Bundle.main.infoDictionary?["DTXcode"] as? String {
if let dtXcodeInteger = Int(dtXcodeString) {
return dtXcodeInteger
}
}
return Int()
}
/**
* Due to searchTextField property who available iOS 13 only, extend this property for iOS 13 previous version compatibility
### Usage Example: ###
````
var searchController: UISearchController?
// Change Search Bar Text Color
searchController?.searchBar.compatibleSearchTextField.textColor = UIColor.XXX
// Change Search Bar Background Color
searchController?.searchBar.compatibleSearchTextField.backgroundColor = UIColor.XXX
````
*/
var compatibleSearchTextField: UITextField {
guard #available(iOS 13.0, *), dtXcode >= 1100 else { return legacySearchField }
return self.searchTextField
}
var legacySearchField: UITextField {
// iOS 13 previous, UISearchBar with both section of UISearchBarBackground and UITextField.
guard let textField = self.subviews.first?.subviews.last as? UITextField else { return UITextField() }
return textField
}
}
//
// UISearchBar+SearchTextField.h
//
@interface UISearchBar (SearchTextField)
/**
* Due to searchTextField property who available iOS 13 only, extend this property for iOS 13 previous version compatibility
### Usage Example: ###
````
// Change Search Bar Text Color
_searchBar.compatibleSearchTextField.textColor = [UIColor XXX];
// Change Search Bar Background Color
_searchBar.compatibleSearchTextField.backgroundColor = [UIColor XXX];
````
*/
@property (nonatomic, readonly) UITextField *compatibleSearchTextField;
@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
// This condition is for Xcode 10 build iOS 13:
return (UITextField *)[self valueForKey:@"searchField"];
#endif
}
else {
// iOS 13 previous, UISearchBar with both section of UISearchBarBackground and UITextField.
return [[[self.subviews firstObject] subviews] lastObject];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment