The cancel button of UISearchController

About the setting of UISearchController is not said, you can refer to the “UISearchController imitation wechat search box” or search online. I want to realize the function of the search box at the top of the wechat address book, but I am stuck in the setting of the cancel button of the search box. I searched all over the Internet, but there is no suitable method. After unremitting exploration, I finally find a solution and come to record it.

plan

Add two properties

// Record whether the cancel button has been found
lazy var hasFindCancelBtn: Bool = {
    return false} ()// Timer (used to find the cancel button periodically)
lazy var link: CADisplayLink = {
    CADisplayLink(target: self, selector: #selector(findCancel))
}()
Copy the code

Provides a way to find and set a cancel button

func findCancel(a) {
    let btn = searchBar.value(forKey: "_cancelButton") as AnyObject
    if btn.isKind(of: NSClassFromString("UINavigationButton")! {LXFLog("That's it.")
        link.invalidate()
        link.remove(from: RunLoop.current, forMode: .commonModes)
        hasFindCancelBtn = true
        let cancel = btn as! UIButton
        cancel.setTitleColor(UIColor.red, for: .normal)
        cancel.setTitleColor(UIColor.orange, for: .highlighted)
    }
}
Copy the code

Proxy method

Sets the proxy to the current controller and implements the proxy method

searchBar.delegate = self
Copy the code
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    if! hasFindCancelBtn { link.add(to:RunLoop.current, forMode: .commonModes)
    }
}
Copy the code

The effect

Attached is related project: Swift 3.0 high imitation wechat