40

在我的應用程序中,我想要在導航欄中添加圖像(徽標)。我工作了XCode 4.2和iOS 5如何在iPhone應用程序的UINavigationBar中添加圖像

我知道UINavigationBarUIToolBar已在IOS 5更改,因此iOS 4.2的代碼UINavigationBar不會在iOS的5工作

我想支持顯示圖像在4.2和5版本中均爲UINavigationBar

我想在UINavigationBar中顯示圖像,如下面的截圖所示。

Navigation bar image

請在這方面的幫助,如果有任何示例代碼意味着其對我很有幫助。

謝謝!

回答

76

要做到這一點的一種方法是使用UINavigationItem.titleViewUINavigationItem.rightBarButtonItem。就像這樣:

viewController.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourimage.png"]]; 
UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourimage2.jpg"]]];  
viewController.navigationItem.rightBarButtonItem = item;  

這裏我使用UIImageView作爲自定義視圖,但它可以用UIButton自定義圖像。

+0

使用功能的擴展協議將這項工作對於兩者的iOS4和5?它是你試圖添加的'clingle' Logo而不是UINavigationbar的背景圖片嗎? – Illep 2012-02-14 23:38:53

+0

它至少在模擬器上。我不認爲它不應該有任何理由。我不明白你的第二個問題。 – barley 2012-02-16 18:21:31

+0

謝謝。但我注意到在您的示例中沒有發佈項目對象。 – 2012-07-05 11:48:56

32

的另一種方法,而無需使用的viewController

// Create your image 
UIImage *image = [UIImage imageNamed: @"logo.png"]; 
UIImageView *imageview = [[UIImageView alloc] initWithImage: image]; 

// set the image view to the title view 
self.navigationItem.titleView = imageview; 
3

斯威夫特版本: 您可以爲您的視圖控制器

protocol Customizable { 
    var navigationItem: UINavigationItem { get } 
} 

extension Customizable { 
    func setNavBarLogo() { 

     let logo = UIImage(named: "logo") 
     let logoImageView = UIImageView(image: logo) 

     self.navigationItem.titleView = logoImageView 
    } 
} 
相關問題