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

eba*_*unt 53 iphone

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

谢谢.

Jas*_*wig 124

设置navigationItem的titleView

UIImage *image = [UIImage imageNamed:@"image.png"];
self.navigationItem.titleView = [[UIImageView alloc] initWithImage:image];
Run Code Online (Sandbox Code Playgroud)

  • UIImage的大小应该是什么?我试过180*40,但它变得模糊. (2认同)

ram*_*ssa 35

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
Run Code Online (Sandbox Code Playgroud)


kla*_*ter 13

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

self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"] autorelease];
Run Code Online (Sandbox Code Playgroud)

如果您正在创建navigationBar,请自己执行相同的操作,而不是调用self.navigationItemcall:navigationBar.topItem

  • UIImage的大小应该是什么?我试过180*40,但它变得模糊. (4认同)