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");
}