美文网首页SwiftObject-CiOS Development
iOS - Swift UISearchController

iOS - Swift UISearchController

作者: LinXunFeng | 来源:发表于2016-12-29 17:31 被阅读93次

UISearchController�的取消按钮

关于UISearchController�的设置就不多说了,可以参考《UISearchController�仿微信搜索框》或者自行上网查找。
情况
本人想实现微信通讯录上方的搜索框功能,但在搜索框的取消按钮的设置这个卡住,在网上搜了个遍,没有�合适的做法,经过不懈的探索,终于找到解决方案,遂前来记录一下。

方案

添加两个属性

// 记录是否已经找到取消按钮
lazy var hasFindCancelBtn: Bool = {
    return false
}()
// 定时器(用来定时查找取消按钮)
lazy var link: CADisplayLink = {
    CADisplayLink(target: self, selector: #selector(findCancel))
}()

提供查找并设置取消按钮的方法

func findCancel() {
    let btn = searchBar.value(forKey: "_cancelButton") as AnyObject
    if btn.isKind(of: NSClassFromString("UINavigationButton")!) {
        LXFLog("就是它")
        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)
    }
}

代理方法

设置代理为当前控制器,并实现代理方法

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

效果

附上相关项目:Swift 3.0 高仿微信

相关文章

网友评论

    本文标题: iOS - Swift UISearchController

    本文链接:https://www.haomeiwen.com/subject/eddpvttx.html