默認導航欄UINavigationController的標題是文字,通過navigationItem.titleView屬性可以很方便的將其替換成自定義的UIView視圖。
1,使用圖片作為標題
1 2
let
image =
UIImage
(named:
"logo"
)
self
.navigationItem.titleView =
UIImageView
(image: image)
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame:CGRectMake(0, 0, 110, 110))
button.setImage(UIImage(named: "btn3"), forState: .Normal)
button.addTarget(self,action:Selector("titleTapped"),forControlEvents:.TouchUpInside)
self.navigationItem.titleView = button
}
func titleTapped(){
print("tapped")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
3,使用分段選擇控件作為標題
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let items=["電話","短信"] as [AnyObject]
let segmented=UISegmentedControl(items:items)
segmented.center=self.view.center
segmented.selectedSegmentIndex=0 //默認選中第1項
segmented.addTarget(self, action: "segmentDidchange:",
forControlEvents: UIControlEvents.ValueChanged) //添加值改變監聽
self.navigationItem.titleView = segmented
}
func segmentDidchange(segmented:UISegmentedControl){
//獲得選項的索引
print(segmented.selectedSegmentIndex)
//獲得選擇的文字
print(segmented.titleForSegmentAtIndex(segmented.selectedSegmentIndex))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}