9

我只是想向 navigationItem 标题添加图像和文本。这就是我正在做的,但它只显示图像而不是标题。这似乎很容易。

例子 (

self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo_small_white.png"]] autorelease];
self.navigationItem.title = @"Company";
4

4 回答 4

27

这是我的代码:

UIView *myView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 300, 30)]; 
UILabel *title = [[UILabel alloc] initWithFrame: CGRectMake(40, 0, 300, 30)];

title.text = NSLocalizedString(@"My Title", nil);
[title setTextColor:[UIColor whiteColor]];
[title setFont:[UIFont boldSystemFontOfSize:20.0]];

[title setBackgroundColor:[UIColor clearColor]];
UIImage *image = [UIImage imageNamed:@"MyLogo.png"];
UIImageView *myImageView = [[UIImageView alloc] initWithImage:image];

myImageView.frame = CGRectMake(0, 0, 30, 30); 
myImageView.layer.cornerRadius = 5.0;
myImageView.layer.masksToBounds = YES;
myImageView.layer.borderColor = [UIColor lightGrayColor].CGColor;
myImageView.layer.borderWidth = 0.1;

[myView addSubview:title];
[myView setBackgroundColor:[UIColor  clearColor]];
[myView addSubview:myImageView];
self.navigationItem.titleView = myView;
于 2012-06-20T01:56:22.517 回答
10

通过设置自定义标题视图,您将替换通常显示标题文本的标准视图。从 in 的文档titleViewUINavigationItem

如果将此属性设置为自定义标题,则会显示它而不是标题。

所以你需要添加你自己的视图(可能是 a UILabel)来显示你的标题——这样做的一种方法是将 aUILabelUIImageView上面添加为容器的子视图,并将UIView设置为.titleView

于 2010-12-10T18:55:12.263 回答
4

斯威夫特 2 中:

var myView: UIView = UIView(frame: CGRectMake(0, 0, 300, 30))
var title: UILabel = UILabel(frame: CGRectMake(40, 0, 300, 30))
title.text = "The Title"
title.textColor = UIColor.blackColor()
title.font = UIFont.boldSystemFontOfSize(20.0)
title.backgroundColor = UIColor.clearColor()
var image: UIImage = UIImage(named: "your-image")!
var myImageView: UIImageView = UIImageView(image: image)
myImageView.frame = CGRectMake(0, 0, 30, 30)
myImageView.layer.cornerRadius = 5.0
myImageView.layer.masksToBounds = true
myImageView.layer.borderColor = UIColor.lightGrayColor().CGColor
myImageView.layer.borderWidth = 0.1
myView.addSubview(title)
myView.backgroundColor = UIColor.clearColor()
myView.addSubview(myImageView)

self.navigationItem.titleView = myView

相关问题:titleView 自动居中,如果上面的示例不是这种情况,那么您可能使用的是较小的屏幕尺寸(例如 iPhone)。只需根据需要将 UIView 和 UILabel 的宽度从 300 更改为更小。当有空间时,它会弹回中心。

于 2015-12-15T13:25:10.963 回答
0
UIImage *image = [UIImage imageNamed:@"image.png"]; // Image name with extension

self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:image] autorelease];

这可能是做到这一点的最短方法。

于 2013-12-11T17:31:51.147 回答