在 navigation bar 中間加上美麗圖片

在 navigation bar 的中間顯示文字,或是左右兩邊顯示 button,都不是件太難的事,但是如果想在中間顯示美麗的圖片呢 ?

當然可以 ! 只要你的 controller 加了 navigation item,想要它顯示文字標題,左右 button,或是美麗圖片都不是問題。

方法 1: 不寫程式的方法

1 在 controller 上加入 navigation item。

2 將 View 貼到 controller 畫面上方 bar 的中間。

你可能會覺得奇怪,明明加了 view,卻看不到它。原因很簡單,當你點選 navigation item 下的 view 時,將發現它的 Width & Height 都是 0。

當你把它的 Width 設為 200,Height 設為 30 時,即可看到它的存在。

而且 Xcode 很聰明,還會自動讓它置中,調整它的 X & Y 座標。

3 將剛剛加入的 View 的 Background 設為 Clear Color,因為我們其實不想看到它,它只是被我們利用的工具人,一個用來放圖片的容器。

4 將 image view 加到 view 上,將它的 X, Y 設為 0,Width & Height 設成和 view 一樣的大小,讓它剛好佔滿整個 view。

5 設定 image view 的圖片。

navigation bar 終於可以顯示漂亮的圖片了 !

也許有人會想到,為何不直接在 navigation bar 上加 image view,而要畫蛇添足,多一層看不到的 view 呢 ? 這算是 Interface Builder 的限制,我們也只能乖乖接受。

如果你想要與眾不同,甚至可以故意將 image view 的高度調大一點,讓它超出 navigaton bar !

其實不只是圖片,有了放在 navigation bar 中間的 view,現在你可以在 view 上加入任何元件,你想呈現什麼樣的內容都可以,這時候就不是技術問題,而是美術天份的問題了 !

方法 2: 寫程式的方法

設定 navigationItem 的屬性 titleView。

override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.navigationItem.titleView = UIImageView(image: UIImage(named: “peterpan”))}

如果希望圖片超出 navigation bar 的話,則必須採用類似方法一的做法,先以一個 UIView 元件當容器,然後在上面放 UIImageView 元件。為何要多一層呢 ? 因為 tittleView 有大小限制,最高 44 points。所以我們要把高度超過 44 的 imag view 放在 tittleView 上,如此它才能完整顯示。

override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.let imageView = UIImageView(image: UIImage(named: “peterpan”))imageView.frame = CGRect(x: 0, y: 0, width: 200, height: 80)navigationItem.titleView = UIView()imageView.backgroundColor = UIColor.bluenavigationItem.titleView?.addSubview(imageView)}

雖然圖片的高度可以超過 navigation bar,不過你可能會遇到一個問題,當你進到下一頁,再返回前一頁時,圖片超出 navigation bar 的部分就被切掉了。這是因為 clipsToBounds 被設成 ture 的關係。

依目前實驗的結果,你可以在前一頁的 controller 加入以下 function,將 imageView.superview?.superview?.superview?.clipsToBounds 設成 false 解決此問題。(假設 imageView 是你在 navigation bar 上顯示的圖片)

override func viewDidAppear(_ animated: Bool) {   super.viewDidAppear(animated)   imageView.superview?.superview?.superview?.clipsToBounds = false}

彼得潘的 Swift iOS App 開發問題解答集

彼得潘的 iOS App Neverland

Written by

彼得潘的 Swift 程式設計入門,App程式設計入門作者,彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,http://apppeterpan.strikingly.com

彼得潘的 Swift iOS App 開發問題解答集

彼得潘和學生們在開發 iOS App 路上曾經解決的問題集

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade