Kirill
Kirill

Reputation: 1472

Add button with image to UISearchBar

I use custom UISearchBar and I override function "draw":

class MySearchBar: UISearchBar {
    override func draw(_ rect: CGRect) {
        if let index = indexOfSearchFieldInSubviews() {
            self.showsCancelButton = false
            searchField.clearButtonMode = .never
        }
    }

    func indexOfSearchFieldInSubviews() -> Int! {        
        var index: Int!
        let searchBarView = subviews[0]        
        for i in 0 ..< searchBarView.subviews.count {
            if searchBarView.subviews[i].isKind(of: UITextField.self) {
                index = i
                break
            }
        }

        return index
    }
}

How can I add this button with red image inside UISearchBar?

custom UISearchBar

Upvotes: 0

Views: 2739

Answers (2)

Kirill
Kirill

Reputation: 1472

Need to add this code inside function draw(_ rect: CGRect):

let img = UIImage(named: "openFullList")
let imageButton = UIButton(type: .custom)
imageButton.frame = CGRect(x: self.frame.width - (img?.size.width)!, y: (self.frame.height - (img?.size.height)!)/2.0, width: (img?.size.width)!, height: (img?.size.height)!)
imageButton.setImage(img, for:UIControlState.normal)
self.addSubview(imageButton)

Upvotes: 1

beyowulf
beyowulf

Reputation: 15331

A UISearchBar is just a subclass of UIView. I suppose you could add a UIButton as you would any other view.

However, there is already a button at the location you want to add your button. UISearchBar comes with a bookmarks button that you can set a custom image on (by calling setImage(someImage, for: .bookmark, state: .normal)). This button has a UISearchBarDelegate method from which you can respond to touch-up-inside events.

func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar)
{
    print("The button on the right side of my search bar was pressed")
}

I find this approach clearer than trying to guess the appropriate size and placement for a custom button, the "bookmark" misnomer not withstanding.

I would also recommend not overriding draw(_ rect:) for initialization and property setting. There is a performance cost to overriding it, and only custom drawing code needs to be there.

Upvotes: 7

Related Questions