swift 4.2实现工具栏
代码:
import UIKit
class ViewController: UIViewController {
var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let screen = UIScreen.main.bounds
let toolbarHeight: CGFloat = 44 //默认高度
//1. 添加Toolbar
let toolbar = UIToolbar(frame: CGRect(x: 0, y: screen.size.height - toolbarHeight, width: screen.size.width, height: toolbarHeight))
//save是系统按钮,使用构造函数initWithBarButtonSystemItem:target:action:
let saveButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.save, target: self, action: #selector(ViewController.save(_:)))
//open不是系统按钮,使用构造函数initWithTitle:Style:target:action:
let openButtonItem = UIBarButtonItem(title: "Open", style: UIBarButtonItem.Style.plain, target: self, action: #selector(ViewController.open(_:)))
//创建"可变空格",属于系统按钮,样式使用UIBarButtonSystemItem中的flexibleSpace成员("固定空格"则使用.fixedSpace成员)
let flexibleButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
//UIToolbar对象的items属性,用于设置工具栏中按钮的集合
toolbar.items = [saveButtonItem,flexibleButtonItem,openButtonItem]
self.view.addSubview(toolbar)
//2. 添加标签
let labelWidht: CGFloat = 84
let labelHeigh: CGFloat = 21
let labelTopView: CGFloat = 250
self.label = UILabel(frame: CGRect(x: (screen.size.width - labelWidht)/2, y: labelTopView, width: labelWidht, height: labelHeigh))
self.label.text = "Label"
//字体左右居中
self.label.textAlignment = .center
self.view.addSubview(self.label)
}
@objc func save(_ sender:AnyObject){
self.label.text = "点击Save"
}
@objc func open(_ sender:AnyObject){
self.label.text = "点击Open"
}
}
image.png
关于"可变空格"和"固定空格":
image.png