2011-03-22 33 views
1

好的,我正在努力做这项工作,但没有成功。 基本上我想添加一个UILabel到UIView并居中。UILabel的SetCenter问题

的代码看起来是这样的:

UIView *customTitleView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 44.0)]; 
[customTitleView setBackgroundColor:[UIColor clearColor]]; 

// Screen title 
CGSize constraint = CGSizeMake(200.0, 44.0f); 
CGSize size = [screenTitle sizeWithFont:[UIFont boldSystemFontOfSize:20.0] 
         constrainedToSize:constraint 
          lineBreakMode:UILineBreakModeCharacterWrap]; 

UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, size.width, size.height)]; 
[titleLabel setText:screenTitle]; 
[titleLabel setTextColor:[UIColor whiteColor]]; 
[titleLabel setFont:[UIFont boldSystemFontOfSize:20.0]]; 
[titleLabel setBackgroundColor:[UIColor clearColor]]; 

titleLabel.center = customTitleView.center; 

[customTitleView addSubview:titleLabel]; 
[titleLabel release]; 

self.navigationItem.titleView = customTitleView; 
[customTitleView release]; 

我预期的UILabel将UIView的内居中。 好吧,事实并非如此。它在某种程度上对齐,甚至不接近UIView的中心。

我在做什么错?

+0

我只是试着用你的代码逐字,它对我来说正确工作(标签正确地居中在视图中)。也许别的东西正在干扰它呢? – jnic 2011-03-22 16:04:46

+0

Ooops,我忘了提及自定义UIView将从顶部导航栏中替换titleView属性。我会更新发布的代码。 – TeodorC 2011-03-22 16:08:54

+0

尝试 'UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(customTitleView.frame.size.width/2-size.width/2, customTitleView.frame.size.height/2-size.height/2, size.width)];;' 初始化titleLabel – Seega 2011-03-22 16:11:32

回答

0

因此,这里是什么地方出了错:

self.navigationItem.titleView = customTitleView; 

当您设置customTitleView作为导航项目的customTitleView框架将改变的标题视图。 customTitleView不再是320像素宽,但titleLabel的帧将保持不变。因此它将不再居中。

难道你不能只将titleLabel设置为titleView?我认为它应该自动居中。如果不是,我知道一个更复杂的方法来解决它。放下评论,我会告诉你如何。

编辑:所以这里是你如何在customTitleView的框架已经改变后重新调整titleLabel

当视图的帧发生变化时layoutSubviews在该视图上被调用。因此,不要让customTitleView成为常规的UIView,您需要将其作为继承自UIView的自定义视图。在该自定义视图中,您可以覆盖layoutSubviews,并在您的实施layoutSubviews中确保根据新框架(self.frame)确保所有内容都以您想要的方式对齐。我将把实施留给你。

+0

感谢您清除问题所在。事情是,titleLabel不是唯一需要留在顶部导航栏上的视图。我仍然有两个右对齐的按钮。但的确,如果我直接将titleLabel设置为titleView,那么yes就是默认居中。 – TeodorC 2011-03-22 17:02:22

+0

@TeodorC如果您使用'self.navigationItem.rightBarButtonItem'和/或'self.navigationItem.leftBarButtonItem',这应该不成问题。 – 2011-03-22 17:07:12

+0

@Erik self.navigationItem.rightBarButtonItem只设置1个按钮,对吧?如果我有2个按钮,那么我不能使用self.navigationItem.rightBarButtonItem。 – TeodorC 2011-03-22 17:09:45