How to make searchbar corner round

2019-07-13 03:34发布

问题:

I am trying to make searchBar corner rounded. I have tried many ways of using layer.cornerRadius, maskToBound = true. I am loading the searchBar in the navigationBar programmatically. I have tried many solution given on stack-overflow but nothing worked.

func setupsearchbar()
{
    //      Setup the Search Controller
    searchcontroller.searchResultsUpdater = self as? UISearchResultsUpdating
    searchcontroller.hidesNavigationBarDuringPresentation = false
    searchcontroller.searchBar.placeholder = "Search" 
    self.navigationItem.titleView = searchcontroller.searchBar
    self.searchcontroller.searchBar.layer.cornerRadius = 30
    self.searchcontroller.searchBar.layer.masksToBounds = true
    definesPresentationContext = true
    searchcontroller.searchBar.delegate = self
}

Please help if there is anything I can do.

回答1:

Use following code which are working fine for me in my current project.

if let textfield = searchController.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;
    }
}

I hope this will help you.