如何将图像和标签添加到UINavigationBar作为标题?

8

目前我只知道如何使用以下代码将字符串作为标题:

[self setTitle:@"iOS CONTROL"];

或者一张带有标签的图片。
self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon.png"]];

但不可以同时进行

有解决方案吗?谢谢

2个回答

16

您可以创建一个 UIView 并添加任意数量的子视图。例如:

UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 40.0)];
titleView.backgroundColor = [UIColor clearColor];

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon.png"]];

UILabel *titleLabel = [[UILabel alloc] init];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textColor = [UIColor redColor];
titleLabel.text = @"My Title Label";
[titleLabel sizeToFit];

...

// Set the frames for imageView and titleLabel to whatever you need them to be

...

[titleView addSubview:imageView];
[titleView addSubview:titleLabel];

self.navigationItem.titleView = titleView;

谢谢,它似乎可以工作,但标签文本没有显示。 - The Fonz
@MaxPuis:我已经更新了我的答案,以适当地设置UILabel的文本颜色和大小。 - Vinny Coyne

1
创建一个新的UIView,将一个UIImage和一个UILabel作为其子视图添加到其中,然后按照自己的方式将该UIView添加使用self.navigationItem.titleView

我需要在每个屏幕上添加它吗? - Kishore Kumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接