import UIKit
class ViewController: UIViewController {
@IBOutlet weak var toolBar: UIToolbar!
@IBOutlet weak var addActionLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
configureToolbar();
}
//配置tool bar Item 函数
func configureToolbar(){
let toolbarButtonItem = [addButtonItem,
flexibleSpaceBarButtonItem,
cameraButtonItem]
toolBar.setItems(toolbarButtonItem, animated: true);
}
//tool bar 系统添加按钮 item
var addButtonItem:UIBarButtonItem{
return UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "AddAction:")
}
//tool bar 系统照相按钮 item
var cameraButtonItem:UIBarButtonItem{
return UIBarButtonItem(barButtonSystemItem:.Camera, target:self, action: "cameraAction:")
}
//item
之间直接弹簧
弹簧
var flexibleSpaceBarButtonItem: UIBarButtonItem {
return UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
}
//添加按钮事件
func AddAction(barButtonItem:UIBarButtonItem ){
addActionLabel.text = "add action something"
print("add action something")
}
//照相按钮事件
func cameraAction(barButtonItem:UIBarButtonItem ){
addActionLabel.text = "camera something"
print("camera something")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//自定义
var customButtonItem:UIBarButtonItem{
return UIBarButtonItem(title:"ToolBar", style:.Done, target: self, action: "CustomAction:")
}
如何添加上图中需要个弹簧 和一个点击事件方法
//item 之间弹簧
var flexibleSpaceBarButtonTwo:UIBarButtonItem{
return UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil);
}
//自定义Item事件
func CustomAction(customBarButtonItem:UIBarButtonItem){
addActionLabel.text = "custom something"
}
最重要修改配置函数,把新添加的item 放入数组里
//配置tool bar Item 函数
func configureToolbar(){
let toolbarButtonItem = [addButtonItem,
flexibleSpaceBarButtonItem,
cameraButtonItem,flexibleSpaceBarButtonTwo,customButtonItem]
toolBar.setItems(toolbarButtonItem, animated: true);
}
如何你觉得太难看了,好吧,我们可以把buttonItem 添加自己的背景图片,在做项目中经常都是这丫做的
在oc 中 我们可以改变toolbar的style 和tincolor 同样我们在查看swift toolbar api 的时候我们也会看见相同的API
看下api
// enum UIBarStyle : Int {
//
// case Default
// case Black
//
// // Deprecated. Use UIBarStyleBlack
// case BlackTranslucent // Deprecated. Use UIBarStyleBlack and set the translucent property to YES
// }
我就设置下 黑色透明的吧
toolBar.barStyle = .BlackTranslucent
toolBar.translucent = true;
toolBar.tintColor = UIColor.greenColor()
var customImageButtonIte:UIBarButtonItem{
return UIBarButtonItem(image:UIImage(named:"test"), style: .Done, target: self, action: "CustomImageButtonItem");
}