Iphone / Ipad将图像和文本添加到导航标题

时间:2010-12-10 18:05:15

标签: iphone ios uiimage uinavigationbar uinavigationitem

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

示例(

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

4 个答案:

答案 0 :(得分: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;

答案 1 :(得分:10)

通过设置自定义标题视图,您将替换通常显示标题文本的标准视图。来自titleView中的UINavigationItem文档:

  

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

因此,您需要添加自己的视图(可能是UILabel)来显示您的标题 - 执行此操作的一种方法是在上面添加UILabelUIImageView作为子视图容器UIView的设置,并将 设置为titleView

答案 2 :(得分:4)

Swift 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改为更小即可。当有空间时,它会重新回到中心。

答案 3 :(得分:0)

UIImage *image = [UIImage imageNamed:@"image.png"]; // Image name with extension

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

这可能是最短的方式。