在UISearchBar中更改UITextField高度 - Swift 3

时间:2016-09-02 22:07:50

标签: ios uitextfield uisearchbar swift3 xcode8

有没有办法改变UISearchBar的textField的高度?

我可以像这样访问textField,虽然背景颜色发生了变化,但框架/尺寸似乎没有任何变化......

我可以通过设置约束来更改IB中的searchBar高度。 但是文本区保持不变(44)......

 override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.mySearchBar.layoutIfNeeded()
        self.mySearchBar.layoutSubviews()
        self.mySearchBar.backgroundColor = UIColor.blue

        for subView in mySearchBar.subviews
        {
            for subsubView in subView.subviews
            {
                if let textField = subsubView as? UITextField
                {
                    var currentTextFieldBounds = textField.bounds
                    textField.borderStyle = UITextBorderStyle.none
                    currentTextFieldBounds.size.height = self.mySearchBar.bounds.height-10

                    textField.bounds = currentTextFieldBounds

                    textField.backgroundColor = UIColor.red

                }
            }
        }

enter image description here

1 个答案:

答案 0 :(得分:0)

UITextField中的UISearchBar无法直接访问。您可以创建自己的UISearchBar子类来模拟常规搜索栏。您可以根据需要使用“界面”构建器或以编程方式完全自定义UI。

protocol SearchBarEventDelegate {
    func searchButtonPressed(searchBar: CustomSearchBar)
    func searchBarDidReceiveInput(searchText: String)
    func searchBarDidBackspace(searchText: String)
}

class CustomSearchBar: UIView {

    var searchTextField: UITextField?
    var delegate : SearchBarEventDelegate?

    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(searchTextField())
    }

    func searchTextField() -> UITextField {
        //Input custom frame and attributes here.
        let textField = UITextField(frame: CGRectZero) 
        textField.delegate = self
        return textField
    }
}

extension CustomSearchBar : UITextFieldDelegate {
     //Implement Textfield delegate methods here. 
     //Propagate events to CustomSearchBar delegate. Example Provided.
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let partialSearchString = textField.text!
        let fullSearchString = (partialSearchString as NSString).stringByReplacingCharactersInRange(range, withString: string)

        if(range.length == 1) {
            delegate?.searchBarDidBackspace(fullSearchString)
        } else {
            delegate?.searchBarDidReceiveInput(fullSearchString)
        }

        return true
    }
}