swift UItextField实现搜索功能

2022-01-13  本文已影响0人  路有点颠簸
image.png
let searchTextField = UITextField()
searchTextField.placeholder = "请输入关键字"
        searchTextField.font = .font(14)
        //右侧删除
        searchTextField.clearButtonMode = .whileEditing
        searchTextField.tintColor = .titleColor_222222
        searchTextField.returnKeyType = .search
        searchTextField.delegate = self
        searchTextField.addTarget(self, action: #selector(searchDidChange(tf:)), for: .editingChanged)
        
        //设置左侧放大镜
        let leftView = UIView()
        leftView.frame = CGRect(x: 5, y: 0, width: 35, height: 35)
        let imgV = UIImageView()
        imgV.image = loadImgName(imageName: "base_search")
        imgV.frame = leftView.bounds
        imgV.contentMode = .center
        leftView.addSubview(imgV)
        
        searchTextField.leftView = leftView
        //设置为空内容才显示放大镜,输入时不显示放大镜.unlessEditing  如要一直显示设置.always
        searchTextField.leftViewMode = .always
        searchTextField.contentVerticalAlignment = .center
        
        bgView.addSubview(searchTextField)

searchTextField.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }


extension LNavSearchView: UITextFieldDelegate {
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return true
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        uLog("点击搜索")
        return true
    }
    
    @objc func searchDidChange(tf: UITextField) {

    }
}

上一篇下一篇

猜你喜欢

热点阅读