【发布时间】:2016-10-19 15:30:57
【问题描述】:
我想在 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的frame size。
但是,我似乎无法让它工作。如果我插入的帧大小为 0,0,100,40;然后它显示框架,但所有内容都被挤压在一起。但是你看到了。我知道 100 应该是动态的以确保显示标题。
但我似乎无法弄清楚。
有什么帮助吗?
【问题讨论】:
-
使用
sizeToFit。这是文档developer.apple.com/reference/uikit/uiview/…。 -
导航栏会自动调整视图大小吗?如果是这样,也许你应该在 XIB 中制作它,以便在调整大小时可以轻松查看它的外观。
标签: ios objective-c uiview uinavigationcontroller uinavigationitem