0

I used UISearchBar in the project, but I can't change the view of it. I want to set border around the search bar.

Can I change UIsearchbar as the same as this image?

enter image description here

Ahmed Lotfy
  • 3,806
  • 26
  • 28

4 Answers4

0

You can set invisible searchbar with transparent borders and background and below that just add image/draw subview if the shape you want. I think Adding UIView with property explicitly: layer.cornerRadius = 4.0 should work :)

Dominik Bucher
  • 2,120
  • 2
  • 16
  • 25
0

Yes you can definitely change the appearance of UISearchbar to the image displayed.

Basically you will need to customise the properties of UISearchBar and associated UITextField and modify the visibility of the search button.

I found "the" article which will help you to achieve the desired result.

http://en.codecloud.net/989.html

Hope this helps.

aniket.ghode
  • 86
  • 1
  • 9
0

You can customise the appearance of UISearchbar as:

// Get UISearchBar UITextFiled
let txfSearchField = Searchbar.value(forKey: "_searchField") as! UITextField

// set Search Bar texfield corder radius
txfSearchField.layer.cornerRadius = 8.0

// set Search Bar texfield border colour and width
txfSearchField.layer.borderWidth = 2.0
txfSearchField.layer.borderColor = UIColor.lightGray.cgColor

// set Search Bar tintColor.
Searchbar.barTintColor = UIColor.white

// Change the search bar placeholder text color
let placeholderlabels   = txfSearchField.value(forKey: "_placeholderLabel") as! UILabel
placeholderlabels.textColor = UIColor.lightGray
Nikhlesh Bagdiya
  • 4,316
  • 1
  • 19
  • 29
  • Thank you, This is correct code. Only I changes colored to be #446D95 – Ahmed Lotfy Jul 09 '17 at 14:36
  • I wouldn't tag this as right answer because it uses very unsafe ways to retrieve the values and even force unwraps. what if next SDK changes the name of the property you are fetching? – Dominik Bucher Jul 11 '17 at 11:17
0

If you have many custom search bar in different viewControllers. I used the correct answer and made custom class for searchBar. I used it in storyboard.

import UIKit

class CustomSearchBar: UISearchBar {

    func setup(){
        // set Search Bar tintColor.
        self.backgroundImage = UIImage()
        self.barTintColor = UIColor.white

        // Get UISearchBar UITextFiled
        guard let textSearchField = self.value(forKey: "_searchField") as? UITextField else {
            return
        }

        // set Search Bar texfield corder radius
        textSearchField.layer.cornerRadius = 6.0

        // set Search Bar texfield border colour and width
        textSearchField.layer.borderColor = UIColor("#446D95").cgColor
        textSearchField.layer.borderWidth = 1.0
        textSearchField.layer.masksToBounds = true
    }
}

Only Call setup function in viewDidLoad of the viewController that you want to use the searchBar.

override func viewDidLoad(){
    searchBar.setup()
}
Ahmed Lotfy
  • 3,806
  • 26
  • 28