更改 UISearchBar 中的 UITextField 高度 - Swift 3
Posted
技术标签:
【中文标题】更改 UISearchBar 中的 UITextField 高度 - Swift 3【英文标题】:Change UITextField height in UISearchBar - Swift 3 【发布时间】:2016-09-02 22:07:50 【问题描述】:有没有办法改变 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
【问题讨论】:
你找到解决办法了吗? 【参考方案1】:UISearchBar
中的UITextField
不可直接访问。您可以创建自己的 UISearchBar
subclass 来模拟常规搜索栏。您可以使用 Interface builder 或以编程方式完全自定义 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
【讨论】:
谢谢你的例子。我不能接受这个答案,因为在 Swift 3 中尝试实现时有很多错误。以上是关于更改 UISearchBar 中的 UITextField 高度 - Swift 3的主要内容,如果未能解决你的问题,请参考以下文章