Search code examples
swiftuisearchbaruisearchcontrolleruinavigationitem

Curve search bar Swift 4


i had problem to change my search bar design programatically on navigation controller. i just want to make the search bar curve like image below:

enter image description here

i had try a lot of example in stack overflow, but i still failed to change the shape. Here what it looks like now:

enter image description here

and here is the source code, on what have already done:

//MARK for searchBar UI
    searchController.dimsBackgroundDuringPresentation = false
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.searchBar.placeholder = " Search for programs..."
    searchController.searchBar.sizeToFit()
    searchController.searchBar.isTranslucent = false
    searchController.searchBar.backgroundImage = UIImage()
    searchController.searchBar.delegate = self
    navigationItem.titleView = searchController.searchBar
    self.searchController.searchBar.layer.cornerRadius = 20.0
    self.searchController.searchBar.clipsToBounds = true
    // SearchBar text
    let textFieldInsideUISearchBar = searchController.searchBar.value(forKey: "searchField") as? UITextField
    textFieldInsideUISearchBar?.borderStyle = .roundedRect
    textFieldInsideUISearchBar?.font = textFieldInsideUISearchBar?.font?.withSize(14)

and now, i really have no idea how to change it, thanks in advance.


Solution

  • This will help you,

    let searchBar = UISearchBar()
    

    On viewDidLoad()

    searchBar.sizeToFit()
    searchBar.placeholder = "Search"
    self.navigationController?.navigationBar.barTintColor = UIColor.green //this is just for reference
    self.navigationItem.titleView = searchBar
    
    if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
        textfield.textColor = UIColor.blue
        if let backgroundview = textfield.subviews.first {
            backgroundview.backgroundColor = UIColor.blue
            backgroundview.layer.cornerRadius = 20;
            backgroundview.clipsToBounds = true;
        }
    }
    

    Above code will give you following output,

    enter image description here