ios swift search bar color change - ios

I am trying to change the gray area (rectangle area) color of the search bar to a different color (orange). Ive tried using searchBar.barTintColor = but that is only changing the color of the cancel button and not the gray area.
EDIT
class usersVC: UITableViewController, UISearchBarDelegate {
// declare searchBar
var searchBar = UISearchBar()
// default function
override func viewDidLoad() {
super.viewDidLoad()
// implement search bar
searchBar.delegate = self
searchBar.showsCancelButton = true
searchBar.sizeToFit()
searchBar.placeholder = "Search"
searchBar.frame.size.width = self.view.frame.size.width - 30
let searchItem = UIBarButtonItem(customView: searchBar)
self.navigationItem.leftBarButtonItem = searchItem
}

Try this again.
I created this effect by loading a simple image with an orange background, seen below.
searchBar.backgroundImage = UIImage(named: "orange")
Background image:
EDIT 1
Based on your recent comment, I tested this with a programatically created searchbar and it works as well.

Related

iOS Swift - How to move searchBar up when scrolling?

Here is the screenshot of my view:
Now when the user scrolls up, I need to hide this searchBar. When the user scrolls down, I need to show this searchBar. And also it should be gradual, not just show and hide.
Here are my codes right now inside viewDidLoad:
self.searchBar.frame = CGRect(x: 0, y: 0, width: (navigationController?.view.bounds.size.width)!, height: 55)
self.searchBar.barStyle = .default
self.searchBar.isTranslucent = false
self.searchBar.barTintColor = UIColor.groupTableViewBackground
self.searchBar.backgroundImage = UIImage()
self.searchBar.delegate = self
self.view.addSubview(searchBar)
self.definesPresentationContext = true
Also, I set the distance of the tableView to the top to be 55 so that the searchBar does not cover the tableView.
What should I do?
Thanks!
The usual thing is to have a UISearchController and assign its search bar to the view controller's navigation item's searchController property. That causes the search bar to behave as you seem to describe, automatically.
Here's an example from my own code:
let src = SearchResultsController(data: self.sections)
let searcher = UISearchController(searchResultsController: src)
searcher.searchResultsUpdater = src
self.navigationItem.searchController = searcher

How do I get a SearchBar in a TableView to look like the one in the Settings App

In my app I have a TableView that is searchable with a SearBar on top. I added the SearchBar, by dragging one in via the Interface Builder and then making my TableView a UISearchBarDelegate and adding:
searchBar.delegate = self
This results in the following look
What I do want is my SearchBar to look like the one in the Settings App (the one preinstalled on every iOS device) that looks like this
Also, when clicked on, it behaves differently, in that it greys out the rest of the view and removes the title as seen here
Whereas my SearchBar only opens the keyboard and shows a cursor when clicked on.
What do I need to do to achieve this specific look and feel?
You can do it easily by adding UISearchController to navigationBar programmatically. Create UISearchController by using code :
let controller = UISearchController(searchResultsController: nil)
then add it to navigationItem,
controller.searchResultsUpdater = self
controller.obscuresBackgroundDuringPresentation = false
controller.searchBar.placeholder = "Search Candies"
definesPresentationContext = true
if #available(iOS 11.0, *) {
navigationItem.searchController = controller
} else {
navigationItem.titleView = searchController.searchBar
}
Credit : https://www.raywenderlich.com/157864/uisearchcontroller-tutorial-getting-started
You can customize UISearchBar by making a subclass of it:
class CustomSearchBar: UISearchBar {
override init(frame:CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
self.placeholder = "Search"
// Color of the text field (in your case it should be gray)
self.barTintColor = yourGraySearchBarColor
// Color of the cursor (you don't need to change this if you want to stay with the default blue)
self.tintColor = UIColor.white
// Background color of you search bar
self.backgroundImage = UIImage(named: "SearchBarBG")
}
}
To set the background color of your search bar, you have to create an image, which is a square with only your wanted color (in your case light gray), size does not matter, I would set it to 20x20 px.
You can darken the background by adding a semi-transparent gray UIView above the whole screen (except the SearchBar, so it needs to be under the SearchBar). If you adopt UISearchBarDelegate you can add this overlay in the searchBarTextDidBeginEditing(_ searchBar: UISearchBar) function and remove it in the searchBarTextDidEndEditing(_ searchBar: UISearchBar) function.

Text in UISearchBar doesn't highlight

Here is an image of the issue:
As you can see the text is highlighted (select all) was pressed, however, as you can see the text isn't actually highlighted.
I don't think it matters but this search bar isn't searching local data it's using Algolia.
My class in implementing UISearchBarDelegate the search bar is created in code not interface builder and the only method implemented is searchBarSearchButtonClicked which I can include code for, but I don't think it's needed. Additionally, this VC is inside a navigation controller
Code:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 135;
searchBar.placeholder = "Search"
searchBar.delegate = self
navigationItem.titleView = searchBar
tableView.delegate = self
tableView.dataSource = self
self.edgesForExtendedLayout = UIRectEdge()
self.extendedLayoutIncludesOpaqueBars = false
self.automaticallyAdjustsScrollViewInsets = false
}
The effect comes from a white selection color. You can change the selection color by assigning a color to the property tintColor of UISearchBar, or over the appearance for all search bars:
UISearchBar.appearance().tintColor = .black

Remove border between View and Search Bar

So in Xcode I'm trying to create a seamless search bar. So I'm trying to replicate something like this
Note how the status bar is the same color as the search bar. Now here's the result to my approach.
What I did was add a View to cover up the default status bar with the blue background. Then I added a search bar and changed it's background to blue. For some reason I end up getting a black border between the two, which ruins the "seamless" design. Any ideas on how I can remove the black border in Swift?
For iOS 7+:
searchBar.backgroundImage = UIImage()
Otherwise this will work on all iOS versions:
searchBar.layer.borderWidth = 1
searchBar.layer.borderColor = thatBlueColor.CGColor
Swift 4
searchBar.barTintColor = UIColor.white
searchBar.setBackgroundImage(UIImage.init(), for: UIBarPosition.any, barMetrics: UIBarMetrics.default)
Sample image
Upate Sample code for navigation bar and search bar background color:
Navigation bar color
self.navigationController?.navigationBar.barTintColor = .blue
Search bar color
searchBarProperty.backgroundColor = self.navigationController?.navigationBar.barTintColor
Note : Navigation bar and search bar color must be same.
Sample image with blue navigation bar and blue search bar
In Xcode 8.3 and Swift 3
Create an outlet from your search bar to your ViewController (I called mine searchBarOutlet for this example).
Below viewDidLoad insert the following.
self.searchBarOutlet.backgroundImage = UIImage()
You should have the following:
override func viewDidLoad() {
super.viewDidLoad()
self.searchBarOutlet.backgroundImage = UIImage()
When you run your app the lines will be gone (they will still be visible on storyboard).
In my case, beyond the edge of search bar needed to take the edge off also the navigation bar.
C# code:
NavigationController.NavigationBar.ShadowImage = new UIImage();
NavigationController.NavigationBar.SetBackgroundImage (new UIImage (), UIBarMetrics.Default);
Swift code:
self.navigationController.navigationBar.shadowImage = UIImage()
self.navigationController.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
The best solution to remove top and bottom default borders is:
To set a new empty searchBar background layout in viewDidLoad for example:
searchBar.backgroundImage = UIImage()
I found these answers to be more complicated than they needed to be. You can just modify the constraint that is binding the searchBar view and the other view to -1pts so that it overlaps exactly by the height of the searchBar's margin.
I encountered the same situation when I set the statusBar and searchBar translucent.
In this situation, I couldn't resolve with the answers written here however I could solve by the following approach.
put UIVisualEffectView on self.view (view of your VC)
make custom class of searchBar, which background is transparent
(also let statusBar transparent)
(swift4 code)
class TransparentSearchBar: UISearchBar {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
makeTransparentBackground()
}
private func makeTransparentBackground() {
for view in self.subviews {
view.backgroundColor = UIColor.clear
for subview in view.subviews {
if let imageview = subview as? UIImageView {
imageview.image = nil
}
}
}
}
}
somewhere in viewDidLoad (statusBar)
let statusWindow = UIApplication.shared.value(forKey:"statusBarWindow") as! UIView
let statusBar = statusWindow.subviews[0] as UIView
statusBar.backgroundColor = UIColor.clear
in Xcode 13
select the search bar and change the search Style to Minimal

UISearchBar custom corners

I'm trying to create a search bar like this:
But I'm noticing that I'm probably going to have to replace the search bar with my own image because the search bar corners comes out wrong when I set:
self.searchController.searchBar.layer.cornerRadius = 50 // I've tried other numbers besides this too with no luck
self.searchController.searchBar.clipsToBounds = true
If I set this:
self.searchController.searchBar.layer.cornerRadius = self.searchController.searchBar.bounds.height/2
The search bar comes out like this:
Which still isn't exact like in the image.
Is there a way to replace the left and right side of the textfield with an image that way I can use the rounded corners from my custom search bar?
I am using this code UISearchBar but you can use this code with UISearchController.
let searchBar = UISearchBar()
searchBar.sizeToFit()
searchBar.placeholder = "Search"
navigationItem.titleView = searchBar
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 = 14;
backgroundview.clipsToBounds = true;
}
}
You should change the radius of searchTextField inside UISearchBar .
you can do that like this :
searchBar.searchTextField.layer.cornerRadius = 20
searchBar.searchTextField.layer.masksToBounds = true
* searchBar is an outlet of UISearchBar from storyBoard
The issue here is you are setting the corner radius on the UISearchBar, not the UITextField inside it. You can do some sort of hack to get the UITextField, but that's not really recommended.
As you mentioned in your question, you'll need to use custom images and the methods shown here: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UISearchBar_Class/#//apple_ref/doc/uid/TP40007529-CH3-SW40
This IS working for me in swift 3 iOS 10:
searchController.searchBar.layer.cornerRadius = 20
searchController.searchBar.clipsToBounds = true
ez way for searchbarview
for subview & POPUPs [Swift 5]
override func layoutSublayers(of layer: CALayer) {
searchBarPopup.clipsToBounds = true
searchBarPopup.layer.cornerRadius = 10
searchBarPopup.layer.maskedCorners = [ .layerMaxXMinYCorner, .layerMinXMinYCorner]
}

Resources