Search code examples
iosswiftuitextfieldborderuisearchbar

How to add a straight line into UISearchBar next to right Search icon?


I already had a UISearchBar (search icon is bookmarkButton inside searchTextField) like that:

Search Bar

my search bar

searchBar code

private func setupSearchBar() {

        searchBar.translatesAutoresizingMaskIntoConstraints = false
        searchBar.backgroundImage = UIImage()
        searchBar.setImage(UIImage(), for: .search, state: .normal)

        searchBar.showsBookmarkButton = true
        searchBar.setImage(UIImage(systemName: "magnifyingglass")?.withTintColor(self.darklightcolor, renderingMode: .alwaysOriginal).applyingSymbolConfiguration(.init(pointSize: 22)), for: .bookmark, state: .normal)

        cancelButtonSearchBar = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self])
        cancelButtonSearchBar.tintColor = .systemPink

        searchBar.layer.borderColor = darklightcolor.cgColor
        searchBar.layer.borderWidth = 1.5
        searchBar.layer.cornerRadius = 19
        searchBar.layer.backgroundColor = UIColor.clear.cgColor

        searchBar.searchTextField.backgroundColor = .clear

        searchBar.delegate = self

        view.addSubview(searchBar)
    }

Now I want to add a gray line to searchBar next to search icon like this searchbar with line But I cant find anyway to add that line. Can anyone help me?


Solution

  • That separator is not part of UISearchbar. You should not play with the internal view hierarchy of the searchbar since it may change and it is going to break your implementation. There is also something in your code that raises a flag, setting the appearance() for buttons when contained in UISearchbars may lead to unintended tinting of buttons in other searchbars within the app. As a practice if you want to set it for all, I would suggest applying those appearance modifications in a single place, otherwise you will end up looking everywhere in your code for the one place where you set the value.

    The best approach if that design is so important would be to implement something custom, at that point, it would be up to you to make the hierarchy and you could modify the hierarchy because it was created by you.

    That being said, if you still want to continue with this approach, you may add this extension:

    extension UISearchBar {
        var cancelButtonView: UIView? {
            self.searchTextField
                .superview?
                .subviews
                .first(where: { $0.description.contains("Button") })
        }
    }
    

    And use it when setting constraints for the view you've added.