我只是想在navigationBar的标题中添加一张图片和文字。这是我的做法,但只显示了图片而没有标题。这似乎很容易实现。
Example (
self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo_small_white.png"]] autorelease];
self.navigationItem.title = @"Company";
我只是想在navigationBar的标题中添加一张图片和文字。这是我的做法,但只显示了图片而没有标题。这似乎很容易实现。
Example (
self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo_small_white.png"]] autorelease];
self.navigationItem.title = @"Company";
这是我的代码:
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;
通过设置自定义标题视图,您可以替换通常显示标题文本的标准视图。从 UINavigationItem
中的 titleView
文档中可以了解到:
如果将此属性设置为自定义标题,则会显示该自定义标题,而不是标题。
因此,您需要添加自己的视图(可能是一个 UILabel
)来显示您的标题-一种方法是将 UILabel
和上面的 UIImageView
作为容器 UIView
的子视图添加,并将其设置为 titleView
。
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更改为更小的值,即可适应屏幕大小。当有足够空间时,它会自动居中。
UIImage *image = [UIImage imageNamed:@"image.png"]; // Image name with extension
self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:image] autorelease];
这可能是实现该目标的最短途径。