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

smc*_*drc 9 iphone uinavigationbar uiimage uinavigationitem ios

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

示例(

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

tes*_*nes 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;
Run Code Online (Sandbox Code Playgroud)


bos*_*acs 10

通过设置自定义标题视图,您将替换通常显示标题文本的标准视图.从titleViewin 的文档UINavigationItem:

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

所以,你需要添加自己的视图(可能是UILabel),以显示你的标题-这样做将增加的一种方式UILabel和UIImageView上面的容器的子视图UIView,并设置该作为titleView.