有没有办法改变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
}
}
}
答案 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
}
}