如何将图像作为导航栏标题

时间:2009-05-14 19:18:41

标签: iphone

我想将.png图像放在导航栏的中间,而不是用文本写的标题。你能告诉我怎么做吗?

感谢。

7 个答案:

答案 0 :(得分:122)

设置navigationItem的titleView

UIImage *image = [UIImage imageNamed:@"image.png"];
self.navigationItem.titleView = [[UIImageView alloc] initWithImage:image];

答案 1 :(得分:34)

Swift 4.2
包括建议的框架/缩放

let image: UIImage = UIImage(named: "image.png")!
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
imageView.contentMode = .scaleAspectFit
imageView.image = image
self.navigationItem.titleView = imageView

答案 2 :(得分:13)

您可以更改UINavigationBar中的所有视图。如果您尝试更改导航控制器中的navigationBar,请执行以下操作:

self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"] autorelease];

如果您正在创建navigationBar,请自行执行相同操作,但不要拨打self.navigationItem来电:navigationBar.topItem

答案 3 :(得分:3)

使用Swift 2.x更新

navigationItem.titleView = UIImageView.init(image: UIImage(named:"yourImageName"))

答案 4 :(得分:1)

如果有人需要在Swift 4.2的导航栏标题视图中同时需要图像和文本,请尝试使用此功能:-

override func viewDidLoad() {

    super.viewDidLoad()

    //Sets the navigation title with text and image
    self.navigationItem.titleView = navTitleWithImageAndText(titleText: "Dean Stanley", imageName: "online")
}

func navTitleWithImageAndText(titleText: String, imageName: String) -> UIView {

    // Creates a new UIView
    let titleView = UIView()

    // Creates a new text label
    let label = UILabel()
    label.text = titleText
    label.sizeToFit()
    label.center = titleView.center
    label.textAlignment = NSTextAlignment.center

    // Creates the image view
    let image = UIImageView()
    image.image = UIImage(named: imageName)

    // Maintains the image's aspect ratio:
    let imageAspect = image.image!.size.width / image.image!.size.height

    // Sets the image frame so that it's immediately before the text:
    let imageX = label.frame.origin.x - label.frame.size.height * imageAspect
    let imageY = label.frame.origin.y

    let imageWidth = label.frame.size.height * imageAspect
    let imageHeight = label.frame.size.height

    image.frame = CGRect(x: imageX, y: imageY, width: imageWidth, height: imageHeight)

    image.contentMode = UIView.ContentMode.scaleAspectFit

    // Adds both the label and image view to the titleView
    titleView.addSubview(label)
    titleView.addSubview(image)

    // Sets the titleView frame to fit within the UINavigation Title
    titleView.sizeToFit()

    return titleView

}

enter image description here

答案 5 :(得分:0)

正在寻找这个问题的答案,我在Apple Discussions forum找到了一个简单明了的解决方案,覆盖了-(void)drawRect:(CGRect)rect的{​​{1}}:

UINavigationBar

答案 6 :(得分:0)

Swift 5版本:

navigationItem.titleView = UIImageView(image: UIImage(named: "logo.png"))