項目中常常會使用 UINavigationController 對各個頁面進行導航,導航欄左側的返回按鈕默認標題文字是上級頁面的title。
但如果上級頁面的標題很長,那麼這個返回按鈕字很多就會很丑:當文字極其長時返回文字就會變成“back”:
let item = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: nil)
self.navigationItem.backBarButtonItem = item;
或者也可以直接把文字設為空字符串,這樣就只有一個箭頭了。
let item = UIBarButtonItem(title: "", style: .Plain, target: self, action: nil)
self.navigationItem.backBarButtonItem = item;
2,在子頁面中設置
import UIKit
class DetailViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let leftBarBtn = UIBarButtonItem(title: "返回", style: .Plain, target: self,
action: "backToPrevious")
self.navigationItem.leftBarButtonItem = leftBarBtn
}
//返回按鈕點擊響應
func backToPrevious(){
self.navigationController?.popViewControllerAnimated(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
二,修改“返回按鈕”圖標
從上面最後一個例子可以看到,在子頁面修改返回按鈕的話只有文字沒有圖片。如果想要使用自定義圖片,或者圖片文字都需要的話可以進行如下操作:
import UIKit
class DetailViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let leftBarBtn = UIBarButtonItem(title: "", style: .Plain, target: self,
action: "backToPrevious")
leftBarBtn.image = UIImage(named: "back")
//用於消除左邊空隙,要不然按鈕頂不到最前面
let spacer = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
spacer.width = -10;
self.navigationItem.leftBarButtonItems = [spacer, leftBarBtn]
}
//返回按鈕點擊響應
func backToPrevious(){
self.navigationController?.popViewControllerAnimated(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
2,既需要圖片也需要文字
這個時候就要通過創建UIButton來實現了
import UIKit
class DetailViewController: UIViewController {
override func viewDidLoad() {
let button = UIButton(type: .System)
button.frame = CGRectMake(0, 0, 65, 30)
button.setImage(UIImage(named:"back"), forState: .Normal)
button.setTitle("返回", forState: .Normal)
button.addTarget(self, action: "backToPrevious", forControlEvents: .TouchUpInside)
let leftBarBtn = UIBarButtonItem(customView: button)
//用於消除左邊空隙,要不然按鈕頂不到最前面
let spacer = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
spacer.width = -10;
self.navigationItem.leftBarButtonItems = [spacer,leftBarBtn]
}
//返回按鈕點擊響應
func backToPrevious(){
self.navigationController?.popViewControllerAnimated(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}