【发布时间】:2014-07-12 14:59:00
【问题描述】:
我想在我的NavigationItem 的titleView 中添加标签和图像。我将UILabel 和UIImageView 添加到UIView 并将其设置为导航项的titleView。正在添加东西,但我无法计算标签的长度并将图像放在它旁边。
我的代码是:-
// Title Name + Image
UIView *titView = [[UIView alloc] initWithFrame:self.navigationItem.titleView.bounds];
self.navigationItem.titleView = titView;
UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(-10, -20, 150, 30)];
title.text = @"Bunny ";
[title setTextColor:[UIColor orangeColor]];
[titView addSubview:title];
float x2 = 30; //+ title.bounds.size.width;
UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"return" ]];
img.frame = CGRectMake(x2, -20, img.bounds.size.width, 30);
[titView addSubview:img];
我正在寻找一些方法来计算宽度文本并相应地设置标签的宽度。现在我将标签的宽度设置为 150。其次,计算 x 位置以将图像放在标签旁边。
尝试了很多方法,但都没有按预期工作。我怎样才能做到这一点?你能不能给出一些指导方针,这样无论标签文本的长度如何,事情都会按预期工作,并且 UIView 被放置在导航项的中心。
非常感谢任何帮助。谢谢。
【问题讨论】:
-
您应该使用布局约束来执行此操作,并在图像视图和标签之间设置水平间距约束。您不需要设置标签的宽度,它会根据字符串自行调整大小。
标签: ios objective-c uiview position