iOS 11 customise search bar in navigation bar - ios

I want to change the color of the text and icon in the iOS 11 searchbar when it is embedded in the navigation bar. So placeholder text, search text and search icon.
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = false
let searchController = UISearchController(searchResultsController: nil)
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
searchController.searchBar.placeholder = "Suchen"
searchController.searchBar.tintColor = .white
}
As you can see in the image, the text is grey on a deep blue background, which looks ugly. I want to text and icon to be at least white. (changing the blue background color also does not work really good, see my other question)
The only thing which works is changing the color of the blinking cursor and the "cancel" button, which is done with the .tintColor property.
Solutions which seems to work in iOS 10 and below seem not work anymore in iOS 11, so please post only solutions which you know working in iOS 11. Thanks.
Maybe I miss the point about this "automatic styling" in iOS 11. Any help is appreciated.

I just found out how to set also the rest of them: (with some help of Brandon, thanks!)
The "Cancel" text:
searchController.searchBar.tintColor = .white
The search icon:
searchController.searchBar.setImage(UIImage(named: "my_search_icon"), for: UISearchBarIcon.search, state: .normal)
The clear icon:
searchController.searchBar.setImage(UIImage(named: "my_search_icon"), for: UISearchBarIcon.clear, state: .normal)
The search text:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white]
Thanks for the help #Brandon!
The placeholder:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
The white background:
let searchController = UISearchController(searchResultsController: nil)
searchController.delegate = self
let searchBar = searchController.searchBar
searchBar.tintColor = UIColor.white
searchBar.barTintColor = UIColor.white
if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
textfield.textColor = UIColor.blue
if let backgroundview = textfield.subviews.first {
// Background color
backgroundview.backgroundColor = UIColor.white
// Rounded corner
backgroundview.layer.cornerRadius = 10;
backgroundview.clipsToBounds = true;
}
}
if let navigationbar = self.navigationController?.navigationBar {
navigationbar.barTintColor = UIColor.blue
}
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
Taken from here.

Put
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
and
UISearchBar.appearance().tintColor = UIColor.white in the AppDelegate.
Alternatively, put them both in [UIViewController viewDidLoad:]

In addition to Darko's answer.
In my case I need to get pure white search textfield color.
Also I need a custom borderLine and cornerRadius.
So if I just set background color to white, set custom corner radius and custom border line I've got something like this.
The problem is that the search bar has some subviews and I've just removed them.
Here is my code:
#interface YourViewController () <UISearchBarDelegate, UISearchControllerDelegate>
// your properties
#property (nonatomic,strong) UISearchController *searchController;
#property (nonatomic,strong) UISearchBar *searchBar;
#end
- (void)viewDidLoad {
[super viewDidLoad];
_searchController = [[UISearchController alloc] initWithSearchResultsController:self.resultsTableController];
_searchController.delegate = self;
_searchController.searchBar.delegate = self;
_searchBar = self.searchController.searchBar;
if (#available(iOS 11.0, *)) {
UITextField *searchTextField = [_searchBar valueForKey:#"searchField"];
if (searchTextField != nil) {
searchTextField.layer.cornerRadius = 4.f;
searchTextField.layer.borderWidth = 1.f;
searchTextField.clipsToBounds = YES;
for (UIView *subView in searchTextField.subviews) {
[subView removeFromSuperview];
}
}
// Color for "Cancel" button
_searchBar.tintColor = [UIColor blackColor];
// Add searchController to navgationBar
_navigationItem.searchController = _searchController;
// Hide searchBar when scroll
_navigationItem.hidesSearchBarWhenScrolling = YES;
}
}
Now I've got a searchBar with pure white background, custom cornerRadius, custom border width. Also I've disabled grey highlight when tap.

Set Search Text Color
(UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]) ).defaultTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
Set Search Placeholder Color
(UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]) ).attributedPlaceholder = [NSForegroundColorAttributeName: UIColor.white]

my two cents for Swift 4.x, lightly cleaned up.
Add in controller or App Delegate:
appearance.backgroundColor = .green
let myFont = UIFont.italicSystemFont(ofSize: 12)
let attribs = [
NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue): myFont,
NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.red
]
appearance.defaultTextAttributes = attribs
in controller:
self.searchBar.barTintColor = .blue
You will get Blue background, green search bar background, red italic font:

I tried Daroko solution, but i had a problem when changing the background to pure white color (it’s was grey).
My solution was to use the setSearchFieldBackgroundImage. also i don't want to rely on apple struct for getting the UITextField
if #available(iOS 11.0, *) {
let whiteImage = UIImage(color: UIColor.white, size: CGSize(width: searchController.searchBar.layer.frame.width, height: searchController.searchBar.layer.frame.height))
searchController.searchBar.setSearchFieldBackgroundImage(whiteImage, for: .normal)
self.navigationItem.searchController = searchController
self.navigationItem.hidesSearchBarWhenScrolling = true
}
public extension UIImage {
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
} }
I used UIImage extension from :
Create UIImage with solid color in Swift

In case someone gets stuck wondering why Darkos solution doesn't work, try changing the UINavigationBar's style to default instead of black. Took me half a day to figure out ¯\_(ツ)_/¯

This code changes the background color of the text field
Swift 4
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//background color of text field
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = .cyan
}
edited: sample of a UISearchBar in cyan

Related

How to make UISearchBar transparent with white text and placeholder

I am using UISearchController extension to setup appearance of my search bar.
I tried insert empty images and other solutions, but still no luck.
Also I can't change search bar text and placeholder to white. It's every-time black and gray correspondently.
There is my extension code:
extension UISearchController {
func setStackedDefaultAppearance() {
self.dimsBackgroundDuringPresentation = false
self.searchBar.setImage(UIImage(named: "search"), for: .search, state: .normal)
let searchBar = self.searchBar
searchBar.tintColor = UIColor.white
searchBar.barTintColor = UIColor.white
searchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
searchBar.scopeBarBackgroundImage = UIImage()
if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
if let backgroundview = textfield.subviews.first {
backgroundview.backgroundColor = UIColor.stackedStatusBarBlue
backgroundview.layer.cornerRadius = 10;
backgroundview.clipsToBounds = true;
}
}
}
}
What I want to achieve that my search bar's color will be the same as navigation bar color:
Kind of transparent background color with no borders.

How to customize the searchBar in a UISearchController?

I know how to set the appearance for a independent UISearchBar, just like the following.
let searchField = searchBar.value(forKey: "searchField") as? UITextField
if let field = searchField {
field.backgroundColor = UIColor.defaultBackgroundColor
field.layer.cornerRadius = 15.0
field.textColor = .white
field.tintColor = .white
field.font = UIFont.systemFont(ofSize: fl(13))
field.layer.masksToBounds = true
field.returnKeyType = .search
}
But this is not working in the UISearchController.
I want to set the text color of the placeholder and the left magnifying lens icon to pure white.
(It seems there is a colored layer over them now).
In addition, the input text is black now, I want it to be white too.
In a conclusion, I want to modify the following properties.
1. textField background color
2. textFiled placeholder text color
3. textFiled text color
4. textFiled font
Anyone know how do it?
Add the following with your code in viewDidAppear:
let placeholderString = NSAttributedString(string: "Placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
field.attributedPlaceholder = placeholderString
let iconView = field.leftView as! UIImageView
iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate)
iconView.tintColor = .white
Updata:
Put those settings in ViewDidAppear() did solve a part of my problem.
But the textfield's background color changed when I set the bar's background color.
Because searchBar.barTintColor = .red is not working in iOS11's UISearchController embedded in navigation item, I used searchBar.backgroundColor = .red
It confused me a lot.
So how to change searchBar's background and textField's background separately?
set attributedPlaceholder for textfield of search bar
#IBOutlet weak var sbSearchBar: UISearchBar!
if let textfield = sbSearchBar.value(forKey: "searchField") as? UITextField {
textfield.backgroundColor = UIColor.red
textfield.attributedPlaceholder = NSAttributedString(string: textfield.placeholder ?? "", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
if let leftView = textfield.leftView as? UIImageView {
leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
leftView.tintColor = UIColor.white
}
}
Here is result:
Update:
I think, this may help you: how to change uitextfield color in searchcontroller?
Just apply your color combination in this code and see.
if #available(iOS 11.0, *) {
let sc = UISearchController(searchResultsController: nil)
sc.delegate = self
let scb = sc.searchBar
scb.tintColor = UIColor.white
scb.barTintColor = UIColor.white
if let textfield = scb.value(forKey: "searchField") as? UITextField {
//textfield.textColor = // Set text color
if let backgroundview = textfield.subviews.first {
// Background color
backgroundview.backgroundColor = UIColor.white
// Rounded corner
backgroundview.layer.cornerRadius = 10;
backgroundview.clipsToBounds = true;
}
}
if let navigationbar = self.navigationController?.navigationBar {
navigationbar.barTintColor = UIColor.blue
}
navigationItem.searchController = sc
navigationItem.hidesSearchBarWhenScrolling = false
}
Result:
Add the following with your code in viewDidAppear:
let placeholderString = NSAttributedString(string: "Placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
field.attributedPlaceholder = placeholderString
let iconView = field.leftView as! UIImageView
iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate)
iconView.tintColor = .white
Update - the following is the complete code to customize UISearchController colors:
override func viewDidAppear(_ animated: Bool) {
//sets navigationbar backgroundColor
if let navigationbar = self.navigationController?.navigationBar {
navigationbar.barTintColor = UIColor.magenta
}
let searchField = searchController.searchBar.value(forKey: "searchField") as? UITextField
//sets searchBar backgroundColor
searchController.searchBar.backgroundColor = .blue
if let field = searchField {
field.layer.cornerRadius = 15.0
//sets text Color
field.textColor = .brown
//sets indicator and cancel button Color
field.tintColor = .green
field.font = UIFont.systemFont(ofSize: 13)
field.layer.masksToBounds = true
field.returnKeyType = .search
//sets placeholder text Color
let placeholderString = NSAttributedString(string: "placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])
field.attributedPlaceholder = placeholderString
//sets icon Color
let iconView = field.leftView as! UIImageView
iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate)
iconView.tintColor = .cyan
//sets textField backgroundColor
if let backgroundview = field.subviews.first {
backgroundview.backgroundColor = UIColor.yellow
}
}
}
The accepted solution does not work for iOS 13, you are getting the following error (testet with Obj-C Code):
Terminating app due to uncaught exception 'NSGenericException',
reason: 'Access to UISearchBar's _searchField ivar is prohibited. This
is an application bug'
But now you have the option to access UISearchBar's TextField directly, without using a private API.
if (#available(iOS 13, *)) {
self.searchController.searchBar.searchTextField.backgroundColor = [UIColor whiteColor];
self.searchController.searchBar.searchTextField.tintColor = [UIColor darkGrayColor];
}
else {
UITextField *txfSearchField = [self.searchController.searchBar valueForKey:#"_searchField"];
UIView *background = txfSearchField.subviews.firstObject;
background.layer.cornerRadius = 10;
background.clipsToBounds = true;
background.backgroundColor=[UIColor whiteColor];
txfSearchField.tintColor=[UIColor darkGrayColor];
txfSearchField.textColor = [UIColor redColor];
}

How to change search bar text color in iOS 11? [duplicate]

I want to change the color of the text and icon in the iOS 11 searchbar when it is embedded in the navigation bar. So placeholder text, search text and search icon.
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = false
let searchController = UISearchController(searchResultsController: nil)
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
searchController.searchBar.placeholder = "Suchen"
searchController.searchBar.tintColor = .white
}
As you can see in the image, the text is grey on a deep blue background, which looks ugly. I want to text and icon to be at least white. (changing the blue background color also does not work really good, see my other question)
The only thing which works is changing the color of the blinking cursor and the "cancel" button, which is done with the .tintColor property.
Solutions which seems to work in iOS 10 and below seem not work anymore in iOS 11, so please post only solutions which you know working in iOS 11. Thanks.
Maybe I miss the point about this "automatic styling" in iOS 11. Any help is appreciated.
I just found out how to set also the rest of them: (with some help of Brandon, thanks!)
The "Cancel" text:
searchController.searchBar.tintColor = .white
The search icon:
searchController.searchBar.setImage(UIImage(named: "my_search_icon"), for: UISearchBarIcon.search, state: .normal)
The clear icon:
searchController.searchBar.setImage(UIImage(named: "my_search_icon"), for: UISearchBarIcon.clear, state: .normal)
The search text:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white]
Thanks for the help #Brandon!
The placeholder:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
The white background:
let searchController = UISearchController(searchResultsController: nil)
searchController.delegate = self
let searchBar = searchController.searchBar
searchBar.tintColor = UIColor.white
searchBar.barTintColor = UIColor.white
if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
textfield.textColor = UIColor.blue
if let backgroundview = textfield.subviews.first {
// Background color
backgroundview.backgroundColor = UIColor.white
// Rounded corner
backgroundview.layer.cornerRadius = 10;
backgroundview.clipsToBounds = true;
}
}
if let navigationbar = self.navigationController?.navigationBar {
navigationbar.barTintColor = UIColor.blue
}
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
Taken from here.
Put
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
and
UISearchBar.appearance().tintColor = UIColor.white in the AppDelegate.
Alternatively, put them both in [UIViewController viewDidLoad:]
In addition to Darko's answer.
In my case I need to get pure white search textfield color.
Also I need a custom borderLine and cornerRadius.
So if I just set background color to white, set custom corner radius and custom border line I've got something like this.
The problem is that the search bar has some subviews and I've just removed them.
Here is my code:
#interface YourViewController () <UISearchBarDelegate, UISearchControllerDelegate>
// your properties
#property (nonatomic,strong) UISearchController *searchController;
#property (nonatomic,strong) UISearchBar *searchBar;
#end
- (void)viewDidLoad {
[super viewDidLoad];
_searchController = [[UISearchController alloc] initWithSearchResultsController:self.resultsTableController];
_searchController.delegate = self;
_searchController.searchBar.delegate = self;
_searchBar = self.searchController.searchBar;
if (#available(iOS 11.0, *)) {
UITextField *searchTextField = [_searchBar valueForKey:#"searchField"];
if (searchTextField != nil) {
searchTextField.layer.cornerRadius = 4.f;
searchTextField.layer.borderWidth = 1.f;
searchTextField.clipsToBounds = YES;
for (UIView *subView in searchTextField.subviews) {
[subView removeFromSuperview];
}
}
// Color for "Cancel" button
_searchBar.tintColor = [UIColor blackColor];
// Add searchController to navgationBar
_navigationItem.searchController = _searchController;
// Hide searchBar when scroll
_navigationItem.hidesSearchBarWhenScrolling = YES;
}
}
Now I've got a searchBar with pure white background, custom cornerRadius, custom border width. Also I've disabled grey highlight when tap.
Set Search Text Color
(UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]) ).defaultTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
Set Search Placeholder Color
(UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]) ).attributedPlaceholder = [NSForegroundColorAttributeName: UIColor.white]
my two cents for Swift 4.x, lightly cleaned up.
Add in controller or App Delegate:
appearance.backgroundColor = .green
let myFont = UIFont.italicSystemFont(ofSize: 12)
let attribs = [
NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue): myFont,
NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.red
]
appearance.defaultTextAttributes = attribs
in controller:
self.searchBar.barTintColor = .blue
You will get Blue background, green search bar background, red italic font:
I tried Daroko solution, but i had a problem when changing the background to pure white color (it’s was grey).
My solution was to use the setSearchFieldBackgroundImage. also i don't want to rely on apple struct for getting the UITextField
if #available(iOS 11.0, *) {
let whiteImage = UIImage(color: UIColor.white, size: CGSize(width: searchController.searchBar.layer.frame.width, height: searchController.searchBar.layer.frame.height))
searchController.searchBar.setSearchFieldBackgroundImage(whiteImage, for: .normal)
self.navigationItem.searchController = searchController
self.navigationItem.hidesSearchBarWhenScrolling = true
}
public extension UIImage {
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
} }
I used UIImage extension from :
Create UIImage with solid color in Swift
In case someone gets stuck wondering why Darkos solution doesn't work, try changing the UINavigationBar's style to default instead of black. Took me half a day to figure out ¯\_(ツ)_/¯
This code changes the background color of the text field
Swift 4
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//background color of text field
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = .cyan
}
edited: sample of a UISearchBar in cyan

UISearchController iOS 11 Customization

I had been using the following code prior to iOS 11 to customize the appearance of the UISearchController search bar:
var searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.setDefaultSearchBar()
searchController.searchResultsUpdater = self
if #available(iOS 11.0, *) {
navigationItem.searchController = searchController
} else {
tableView.tableHeaderView = searchController.searchBar
}
extension UISearchBar {
func setDefaultSearchBar() {
self.tintColor = UIColor.blue
self.searchBarStyle = .minimal
self.backgroundImage = UIImage(color: UIColor.clear)
let searchBarTextField = self.value(forKey: "searchField") as! UITextField
searchBarTextField.textColor = UIColor.white
searchBarTextField.tintColor = UIColor.blue
searchBarTextField = .dark
}
}
However, the appearance of the search bar fails to update when running the same code on iOS 11.
iOS 10:
iOS 11:
Much of the attention to this question so far has focused on the text color of the search bar. I am looking at more than this - the background color, tint color, the search indicator, clear button color, etc.
I just found out how to set them: (with some help of Brandon and Krunal, thanks!)
The "Cancel" text:
searchController.searchBar.tintColor = .white
The search icon:
searchController.searchBar.setImage(UIImage(named: "my_search_icon"), for: UISearchBarIcon.search, state: .normal)
The clear icon:
searchController.searchBar.setImage(UIImage(named: "my_search_icon"), for: UISearchBarIcon.clear, state: .normal)
The search text:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white]
The placeholder:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
The white background:
if #available(iOS 11.0, *) {
let sc = UISearchController(searchResultsController: nil)
sc.delegate = self
let scb = sc.searchBar
scb.tintColor = UIColor.white
scb.barTintColor = UIColor.white
if let textfield = scb.value(forKey: "searchField") as? UITextField {
textfield.textColor = UIColor.blue
if let backgroundview = textfield.subviews.first {
// Background color
backgroundview.backgroundColor = UIColor.white
// Rounded corner
backgroundview.layer.cornerRadius = 10;
backgroundview.clipsToBounds = true;
}
}
if let navigationbar = self.navigationController?.navigationBar {
navigationbar.barTintColor = UIColor.blue
}
navigationItem.searchController = sc
navigationItem.hidesSearchBarWhenScrolling = false
}
Taken from here.
To properly set the text typed into the search bar to white use (when using a dark field color):
searchController.searchBar.barStyle = .black
To set the textfield background color
if #available(iOS 11.0, *) {
if let textfield = searchController.searchBar.value(forKey: "searchField") as? UITextField {
if let backgroundview = textfield.subviews.first {
// Background color
backgroundview.backgroundColor = UIColor.white
// Rounded corner
backgroundview.layer.cornerRadius = 10;
backgroundview.clipsToBounds = true;
}
}
}
However using something like
textfield.textColor = UIColor.blue
in the above does not seem to work.
Try setting the search bar's bar style.
searchController.searchBar.barStyle = UIBarStyleBlack;
Moving the call to setDefaultSearchBar into viewDidAppear should fix this.
You need to find the UISearchBar's underlying UITextField and change its text color.
Notice this only have effect when search controller is going to present (UISearchControllerDelegate.willPresentSearchController) or presented.
class ViewController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// setup your search controller...
// set search controller's delegate
navigationItem.searchController?.delegate = self
}
}
extension ViewController : UISearchControllerDelegate {
func willPresentSearchController(_ searchController: UISearchController) {
// update text color
searchController.searchBar.textField?.textColor = .white
}
}
extension UISearchBar {
var textField: UITextField? {
for subview in subviews.first?.subviews ?? [] {
if let textField = subview as? UITextField {
return textField
}
}
return nil
}
}
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
Try it: searchController.<YOUR SEARCHBAR>.barStyle = .blackOpaque instead of self.searchBarStyle = .minimal.
Thus:
var searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.setDefaultSearchBar()
//Add this line below
searchController.searchBar.barStyle = .blackOpaque
searchController.searchResultsUpdater = self
if #available(iOS 11.0, *) {
navigationItem.searchController = searchController
} else {
tableView.tableHeaderView = searchController.searchBar
}
extension UISearchBar {
func setDefaultSearchBar() {
self.tintColor = UIColor.blue
//Delete this line below
self.searchBarStyle = .minimal
self.backgroundImage = UIImage(color: UIColor.clear)
let searchBarTextField = self.value(forKey: "searchField") as! UITextField
searchBarTextField.textColor = UIColor.white
searchBarTextField.tintColor = UIColor.blue
searchBarTextField = .dark
}
}
If you need to change the background colour of the textField in the searchBar, see my answer here:
https://stackoverflow.com/a/46315974/1109892
You have to access the UITextField inside the UISearchBar. You can do that by using
let textFieldInsideSearchBar = yourSearchbar.value(forKey: "searchField") as? UITextField
textFieldInsideSearchBar?.textColor = yourcolor
OR

Transparent iOS navigation bar

I'm creating an app and i've browsed on the internet and i'm wondering how they make this transparent UINavigationBar like this:
I've added following like in my appdelegate:
UINavigationBar.appearance().translucent = true
but this just makes it look like following:
How can I make the navigation bar transparent like first image?
You can apply Navigation Bar Image like below for Translucent.
Objective-C:
[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
forBarMetrics:UIBarMetricsDefault]; //UIImageNamed:#"transparent.png"
self.navigationController.navigationBar.shadowImage = [UIImage new];////UIImageNamed:#"transparent.png"
self.navigationController.navigationBar.translucent = YES;
self.navigationController.view.backgroundColor = [UIColor clearColor];
Swift 3:
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) //UIImage.init(named: "transparent.png")
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = .clear
Swift Solution
This is the best way that I've found. You can just paste it into your appDelegate's didFinishLaunchingWithOptions method:
Swift 3 / 4
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Sets background to a blank/empty image
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
// Sets shadow (line below the bar) to a blank image
UINavigationBar.appearance().shadowImage = UIImage()
// Sets the translucent background color
UINavigationBar.appearance().backgroundColor = .clear
// Set translucent. (Default value is already true, so this can be removed if desired.)
UINavigationBar.appearance().isTranslucent = true
return true
}
Swift 2.0
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// Sets background to a blank/empty image
UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: .Default)
// Sets shadow (line below the bar) to a blank image
UINavigationBar.appearance().shadowImage = UIImage()
// Sets the translucent background color
UINavigationBar.appearance().backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)
// Set translucent. (Default value is already true, so this can be removed if desired.)
UINavigationBar.appearance().translucent = true
return true
}
source: Make navigation bar transparent regarding below image in iOS 8.1
Swift 5 applying only to the current view controller
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Make the navigation bar background clear
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.isTranslucent = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Restore the navigation bar to default
navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
navigationController?.navigationBar.shadowImage = nil
}
Swift 3 : extension for Transparent Navigation Bar
extension UINavigationBar {
func transparentNavigationBar() {
self.setBackgroundImage(UIImage(), for: .default)
self.shadowImage = UIImage()
self.isTranslucent = true
}
}
Swift 4.2 Solution: For transparent Background:
For General Approach:
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
}
For Specific Object:
override func viewDidLoad() {
super.viewDidLoad()
navBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
navBar.shadowImage = UIImage()
navBar.navigationBar.isTranslucent = true
}
Hope it's useful.
I had been working on this, and I was facing a problem using the responses provided here by different users. Problem was a white box behind my NavigationBar transparent image on iOS 13+
My solution is this one
if #available(iOS 13, *) {
navBar?.standardAppearance.backgroundColor = UIColor.clear
navBar?.standardAppearance.backgroundEffect = nil
navBar?.standardAppearance.shadowImage = UIImage()
navBar?.standardAppearance.shadowColor = .clear
navBar?.standardAppearance.backgroundImage = UIImage()
}
Update
thanks to #TMin
If you use a tableView/CollectionView with this you will notice a 1 point shadow appears when you scroll. Add navBar?.scrollEdgeAppearance = nil to get ride of this shadow.
Hope this helps anyone with same problem
I was able to accomplish this in swift this way:
let navBarAppearance = UINavigationBar.appearance()
let colorImage = UIImage.imageFromColor(UIColor.morselPink(), frame: CGRectMake(0, 0, 340, 64))
navBarAppearance.setBackgroundImage(colorImage, forBarMetrics: .Default)
where i created the following utility method in a UIColor category:
imageFromColor(color: UIColor, frame: CGRect) -> UIImage {
UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
color.setFill()
UIRectFill(frame)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
What it worked for me:
let bar:UINavigationBar! = self.navigationController?.navigationBar
self.title = "Whatever..."
bar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
bar.shadowImage = UIImage()
bar.alpha = 0.0
Set the background property of your navigationBar, e.g.
navigationController?.navigationBar.backgroundColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.5)
(You may have to change that a bit if you don't have a navigation controller, but that should give you an idea of what to do.)
Also make sure that the view below actually extends under the bar.
If you want to be able to do this programmatically in swift 4 while staying on the same view,
if change {
navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.backgroundColor = UIColor(displayP3Red: 255/255, green: 206/255, blue: 24/255, alpha: 1)
navigationController?.navigationBar.barTintColor = UIColor(displayP3Red: 255/255, green: 206/255, blue: 24/255, alpha: 1)
} else {
navigationController?.navigationBar.isTranslucent = true
navigationController?.navigationBar.setBackgroundImage(backgroundImage, for: .default)
navigationController?.navigationBar.backgroundColor = .clear
navigationController?.navigationBar.barTintColor = .clear
}
One important thing to remember though is to click this button in your storyboard. I had an issue with a jumping display for a long time. Make sureyou set this:
Then when you change the translucency of the navigation bar it will not cause the views to jump as the views extend all the way to the top, regardless of the visiblity of the navigation bar.
Add this in your did load
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.0)
//adjust alpha according to your need 0 is transparent 1 is solid
For those looking for OBJC solution, to be added in App Delegate didFinishLaunchingWithOptions method:
[[UINavigationBar appearance] setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
[UINavigationBar appearance].shadowImage = [UIImage new];
[UINavigationBar appearance].backgroundColor = [UIColor clearColor];
[UINavigationBar appearance].translucent = YES;
Try this, it works for me if you also need to support ios7, it is based on the transparency of UItoolBar:
[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [UIImage new];
self.navigationController.navigationBar.translucent = YES;
self.navigationController.view.backgroundColor = [UIColor clearColor];
UIToolbar* blurredView = [[UIToolbar alloc] initWithFrame:self.navigationController.navigationBar.bounds];
[blurredView setBarStyle:UIBarStyleBlack];
[blurredView setBarTintColor:[UIColor redColor]];
[self.navigationController.navigationBar insertSubview:blurredView atIndex:0];
iOS 13.0+ introduced UINavigationBarAppearance because of which, this problem occurs on iOS 13.0+
Use this to solve.
Change Navigation Bar Appearance
Use UINavigationBarAppearance and UIBarButtonItemAppearance to change the appearance of the navigation bar.
// Make the navigation bar's title with red text.
if #available(iOS 13, *) {
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundColor = UIColor.systemRed
appearance.titleTextAttributes = [.foregroundColor: UIColor.lightText] // With a red background, make the title more readable.
navigationItem.standardAppearance = appearance
navigationItem.scrollEdgeAppearance = appearance
navigationItem.compactAppearance = appearance // For iPhone small navigation bar in landscape.
}
Utility method which you call by passing navigationController and color which you like to set on navigation bar. For transparent you can use clearColor of UIColor class.
For objective c -
+ (void)setNavigationBarColor:(UINavigationController *)navigationController
color:(UIColor*) color {
[navigationController setNavigationBarHidden:false animated:false];
[navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
[navigationController.navigationBar setShadowImage:[UIImage new]];
[navigationController.navigationBar setTranslucent:true];
[navigationController.view setBackgroundColor:color];
[navigationController.navigationBar setBackgroundColor:color];
}
For Swift 3.0 -
class func setNavigationBarColor(navigationController : UINavigationController?,
color : UIColor) {
navigationController?.setNavigationBarHidden(false, animated: false)
navigationController?.navigationBar .setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.translucent = true
navigationController?.view.backgroundColor = color
navigationController?.navigationBar.backgroundColor = color
}
Write these two lines:
navigationController?.navigationBar.isTranslucent = true
navigationController?.navigationBar.backgroundColor = .clear
Worked for me in iOS 13
None of the answers here fully worked for me. This makes the navigation bar fully transparent - tested on iOS 14 and iOS 11 (Objective C):
[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [UIImage new];
self.navigationController.navigationBar.translucent = YES;
self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
Anyone looking for a iOS 15+ working version, this is what worked for me, as the old techniques with setBackgroundImage/shadowImage were not working anymore.
To se it transparent:
func setTransparent() {
backgroundColor = .clear
isTranslucent = true
standardAppearance.shadowColor = .clear
standardAppearance.backgroundColor = .clear
standardAppearance.backgroundEffect = nil
scrollEdgeAppearance = standardAppearance
}
To remove transparency:
func removeTransparent() {
setBackgroundImage(nil, for: .default)
shadowImage = nil
backgroundColor = .white
isTranslucent = false
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
standardAppearance = appearance
scrollEdgeAppearance = standardAppearance
}
My implementation of navigation bar configuration as translucent and switching to default state for iOS 15 and older versions:
extension UINavigationBar {
static let defaultBackgroundColor = UIColor.red
static let defaultTintColor = UIColor.white
func setTranslucent(tintColor: UIColor, titleColor: UIColor) {
if #available(iOS 15, *) {
let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
appearance.titleTextAttributes = [.foregroundColor: titleColor]
standardAppearance = appearance
scrollEdgeAppearance = appearance
} else {
titleTextAttributes = [.foregroundColor: titleColor]
setBackgroundImage(UIImage(), for: UIBarMetrics.default)
shadowImage = UIImage()
}
isTranslucent = true
self.tintColor = tintColor
}
func setDefaultState() {
isTranslucent = false
clipsToBounds = false
if #available(iOS 15, *) {
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundColor = UINavigationBar.defaultBackgroundColor
appearance.titleTextAttributes = [.foregroundColor: UINavigationBar.defaultTintColor]
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
} else {
setBackgroundImage(UIImage(), for: UIBarPosition.any, barMetrics: UIBarMetrics.defaultPrompt)
shadowImage = UIImage()
barTintColor = UINavigationBar.defaultBackgroundColor
titleTextAttributes = [.foregroundColor: UINavigationBar.defaultTintColor]
}
tintColor = UINavigationBar.defaultTintColor
}
}
This will defiantly work for swift 4/5 users.
func setUpNavBar(){
navigationItem.title = "Flick"
navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = UIColor.clear
navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]
}
IOS15 Version
extension UIViewController {
func clearNavigationBar(clear: Bool) {
if clear {
let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
self.navigationController?.navigationBar.standardAppearance = appearance
self.navigationController?.navigationBar.scrollEdgeAppearance = appearance
} else {
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
self.navigationController?.navigationBar.standardAppearance = appearance
self.navigationController?.navigationBar.scrollEdgeAppearance = appearance
}
}
}
class ViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
clearNavigationBar(clear: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
clearNavigationBar(clear: false)
}
}
For above all iOS version
if #available(iOS 15.0, *) {
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundImage = UIColor.clear.imageWithColor(width: UIScreen.main.bounds.size.width, height: 84)
appearance.shadowImage = UIImage()
appearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.black ,NSAttributedString.Key.font : UIFont(name: "SF UI Display Semibold", size: 18) ?? UIFont()]
appearance.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: 2)
self.navigationBar.standardAppearance = appearance
} else {
self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.black ,NSAttributedString.Key.font : UIFont(name: "SF UI Display Semibold", size: 18) ?? UIFont()]
self.navigationBar.setTitleVerticalPositionAdjustment(2, for: UIBarMetrics.default)
}
func imageWithColor(width: CGFloat, height: CGFloat) -> UIImage {
let size = CGSize(width: width, height: height)
return UIGraphicsImageRenderer(size: size).image { rendererContext in
self.setFill()
rendererContext.fill(CGRect(origin: .zero, size: size))
}
}
Just add bellow code line inside your application delegate
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
// Sets shadow (line below the bar) to a blank image
UINavigationBar.appearance().shadowImage = UIImage()
// Sets the translucent background color
UINavigationBar.appearance().backgroundColor = .clear
// Set translucent. (Default value is already true, so this can be removed if desired.)
UINavigationBar.appearance().isTranslucent = true
then override your custom nav bar inside your view controller and make sure to reset once it disappear

Resources