How to add image in UINavigationBar in IPhone app

牧云@^-^@ 提交于 2019-11-30 10:34:44

问题


In my app, i want to add image(logo) in Navigation bar. I am working on XCode 4.2 and iOS 5.

I know UINavigationBar, UIToolBar has been changed in iOS 5. So iOS 4.2 UINavigationBar code won't work in iOS 5.

I want to support display image in UINavigationBar in both 4.2 and 5 version.

I want to be display image in UINavigationBar like as in below screenshot.

Please help in this regards and if there is any sample code means its very helpful to me.

Thanks!!!


回答1:


One way to do this is to use UINavigationItem.titleView and UINavigationItem.rightBarButtonItem. Like this :

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;    

Here I am using UIImageView as custom view, but it can be UIButton with custom image.




回答2:


Another way without using a 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:


Swift version: You can create a protocol extension for using the function in your view controllers

protocol Customizable {
    var navigationItem: UINavigationItem { get }
}

extension Customizable {
    func setNavBarLogo() {

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

        self.navigationItem.titleView = logoImageView
    }
}


来源:https://stackoverflow.com/questions/8814056/how-to-add-image-in-uinavigationbar-in-iphone-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!