当前,当选择文本字段并出现键盘时,出现以下UIToolBar
let bar = UIToolbar()
let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let reset = UIBarButtonItem(title: "Tool Bar Text", style: .plain, target: self, action: #selector(functionExample))
reset.tintColor = UIColor.white
bar.barTintColor = UIColor.red
bar.items = [spacer,reset, spacer]
bar.sizeToFit()
exampleTextField = bar
我想调整UIToolBar
的高度以使其占据更多的屏幕,我已经尝试了以下操作,但似乎什么也没做。
bar.frame = CGRect(x: bar.frame.origin.x, y: bar.frame.origin.y, width: bar.frame.size.width, height: 150)
bar.frame = CGRect(x: 0, y: view.frame.size.height - 80, width: view.frame.size.width, height: 80)
我也尝试过:bar.frame = CGRect(x:myToolbar.frame.origin.x,y:bar.frame.origin.y,宽度:myToolbar.frame.size.width,高度:20)
[这两种方法似乎都根本不改变高度。
UPDATE 2:
所以这种方法似乎有效,但是我只希望它在键盘抬起时出现,而不是在视图控制器第一次打开时出现,
let toolBar = UIToolbar()
var items = [UIBarButtonItem]()
items.append(
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
)
items.append(
UIBarButtonItem(title: "Tool Bar Text", style: .plain, target: self, action: #selector(confirmSignature))
)
items.append(
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
)
toolBar.setItems(items, animated: true)
toolBar.tintColor = .white
toolBar.barTintColor = UIColor.red
toolBar.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
let guide = self.view.safeAreaLayoutGuide
toolBar.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
toolBar.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
toolBar.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
toolBar.heightAnchor.constraint(equalToConstant: 80).isActive = true
}
else {
NSLayoutConstraint(item: toolBar, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: toolBar, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: toolBar, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
toolBar.heightAnchor.constraint(equalToConstant: 44).isActive = true
}
exampleTextField.inputAccessoryView = toolBar
view.addSubview(toolBar)
免责声明:在浏览器中键入,未经Xcode测试。
首先在UIViewController
中为工具栏创建一个属性:
let bar: UIToolbar?
然后在viewDidLoad
中,可以像代码中所示的那样设置栏。
现在您需要遵循UITextFieldDelegate
协议,请响应textFieldDidBeginEditing
以显示工具栏:
extension UIViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == myTextField {
bar.isHidden = false
}
}
}
请确保在myTextField.delegate = self
中添加行viewDidLoad
。
应该显示工具栏,现在您可以尝试使用尺寸了。您可以将其再次隐藏在类似的方法内:textFieldDidEndEditing
。