我想在我的UINavigationController中的标题旁边显示一个小图标。
通过Photoshop的魔力,像这样:
我知道我需要创建一个新视图并将图像和标题构建到其中。这就是我在做的事情:
在UINavigationController视图控制器的viewDidLoad中,我调用方法
[self setTitleBar];
调用此方法:
- (void) setTitleBar {
CGRect navBarFrame = self.navigationController.navigationBar.frame;
//UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(navBarFrame.origin.x, navBarFrame.origin.y, (leftButtonFrame.origin.x + leftButtonFrame.size.width) - rightButtonFrame.origin.x, navBarFrame.size.height)];
UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(navBarFrame.origin.x, navBarFrame.origin.y,self.view.frame.size.width,navBarFrame.size.height)];
titleView.backgroundColor = [UIColor clearColor];
CGPoint tvCenter = CGPointMake(titleView.frame.size.width/2, titleView.frame.size.height/2);
UIImage * icon = [UIImage imageNamed:@"star"];
UIImageView *iconView = [[UIImageView alloc] initWithImage:icon];
iconView.frame = CGRectMake(0, 0, icon.size.width, icon.size.height);
UILabel *title = [[UILabel alloc] init];
title.backgroundColor = [UIColor clearColor];
title.textColor = [UIColor whiteColor];
title.textAlignment = NSTextAlignmentCenter;
title.text = @"SOME TITLE";
title.frame = CGRectMake(0, 0, 100, titleView.frame.size.height);
[title sizeToFit];
iconView.center = CGPointMake(tvCenter.x - (icon.size.width/2), tvCenter.y);
[titleView addSubview:iconView];
[titleView addSubview:title];
self.navigationItem.titleView = titleView;
}
我在titleView中的逻辑是:获取最左边按钮的框架并获得最右边的按钮框架。然后做一些数学计算,以确定视图有多大。这应该是titleView的帧大小。
然而,我似乎无法让它发挥作用。如果我插入一个0,0,100,40的帧大小;然后它显示了框架,但一切都被挤压在一起。但是你看到了。我知道100应该是动态的,以确保显示标题。
但我似乎无法弄明白。
任何帮助?
答案 0 :(得分:0)
您可以将对象放置在导航控制器视图上,作为子视图。
- (void) setTitleBar {
//Let's say your icon size is 20
int starSize = 20;
//Now you'll have to calculate where to place the ImageView respect the TextSize (for this you'll need to know the text and font of your UINavigationItem title)
CGSize textSize = [@"SOME TITLE" sizeWithAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"navfontname" size:15]}];
UIImageView *startImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.navigationController.view.frame.size.width/2 - textSize.width/2, self.navigationController.view.frame.size.height/2 - starSize/2, starSize,starSize)];
startImageView.image = [UIImage imageNamed:@"star"];
[self.navigationController.view addSubview:startImageView];
}