细节
- Xcode 10.2.1 (10E1001)、斯威夫特 5
完整样本
import UIKit
class ViewController: UIViewController {
private weak var toolBar: UIToolbar?
override func viewDidLoad() {
super.viewDidLoad()
var bounds = UIScreen.main.bounds
let bottomBarWithHeight = CGFloat(44)
bounds.origin.y = bounds.height - bottomBarWithHeight
bounds.size.height = bottomBarWithHeight
let toolBar = UIToolbar(frame: bounds)
view.addSubview(toolBar)
var buttons = [UIBarButtonItem]()
buttons.append(UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(ViewController.action)))
buttons.append(UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: #selector(ViewController.action)))
buttons.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
buttons.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
buttons.append(ToolBarTitleItem(text: "\(NSDate())", font: .systemFont(ofSize: 12), color: .lightGray))
buttons.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
buttons.append(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(ViewController.action)))
toolBar.items = buttons
self.toolBar = toolBar
}
@objc func action() { print("action") }
}
class ToolBarTitleItem: UIBarButtonItem {
init(text: String, font: UIFont, color: UIColor) {
let label = UILabel(frame: UIScreen.main.bounds)
label.text = text
label.sizeToFit()
label.font = font
label.textColor = color
label.textAlignment = .center
super.init()
customView = label
}
required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
}
结果