右对齐self.navigationItem setTitleView

时间:2013-04-30 09:44:47

标签: iphone ios xcode

我需要将navigationItem TitleView与最右边对齐。 (通常出现navigationItem rightBarButtonItem的地方)

如何做到这一点?

我试过这个但是没有运气它仍然把TitleView放在中心:

CGRect titleViewPos = CGRectMake(300, 0, 200, 10);
self.navigationItem.titleView.frame = titleViewPos;

6 个答案:

答案 0 :(得分:4)

UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
lbl.textAlignment = UITextAlignmentRight;
lbl.backgroundColor = [UIColor clearColor];
lbl.text = @"TITLEVIEW";
self.navigationItem.titleView = lbl;

您将获得输出

enter image description here

答案 1 :(得分:0)

只是一个想法:

 UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
 btn.frame = CGRectMake(300, 0, 200, 10);
 [btn setTitle:@"titleView" forState:UIControlStateNormal];
 self.navigationItem.titleView = btn;

答案 2 :(得分:0)

您需要将UIElement(UIView,UILabel)传递给导航项,然后您可以设置位置并使用导航标题或左键或右键进行其他自定义。 愿这对你有帮助。

答案 3 :(得分:0)

尝试这个,可以使用 -

 UILabel *lbNavTitle = [[UILabel alloc] initWithFrame:CGRectMake(0,40,320,40)];
lbNavTitle.textAlignment = NSTextAlignmentRight;
lbNavTitle.backgroundColor = [UIColor clearColor];
lbNavTitle.text = @"hello World";
self.navigationItem.titleView = lbNavTitle;

答案 4 :(得分:0)

标题视图框架会自动调整,如果您想获得此结果,可以尝试:

UILabel *titleLabel = [[UILabel alloc] initWithFrame:self.navigationController.navigationBar.frame];
[titleLabel setTextAlignment:UITextAlignmentRight];
[titleLabel setText:@"Your title"];
[titleLabel setBackgroundColor:[UIColor clearColor]];
[titleLabel setTextColor:[UIColor whiteColor]];
self.navigationItem.titleView = titleLabel;

注意:请务必不要设置视图控制器的self.title,否则会覆盖titleView

另一个解决方案是将titleLabel放入UIBarButtonItem(customView)并将其设置为self.navigationItem.rightBarButtonItem,这样您就不需要设置文本对齐广告标签的框架可以是适当的文字大小

答案 5 :(得分:0)

这些都不适合我。我接受了Desdanova的建议,并将其添加为子视图。有道理,因为这就是全部!用你想要的任何帧位置初始化它然后

[self.view addSubView:lbl];

和Voila!