SetCenter problem for an UILabel
OK, I'm struggling to make this work but without success. Basically I want to add a UILabel to an UIView and center it.
The code looks like this:
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 setTex开发者_运维知识库t: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];
I expected that the UILabel would be centered within the UIView. Well, it isn't. It is somehow right aligned and not even close to the center of the UIView.
What am I doing wrong?
So here's what's going wrong:
self.navigationItem.titleView = customTitleView;
When you set customTitleView
as the title view of the navigation item the frame of customTitleView
will change. customTitleView
won't be 320 pixels wide anymore, but the frame of titleLabel
will remain the same. Thus it will no longer be centered.
Can't you just set titleLabel
as titleView
? I think it should be centered automatically. If not, I know a more complicated way to solve it. Drop a comment and I'll tell you how.
EDIT: So here is how you realign the titleLabel
after customTitleView
's frame has changed.
When the frame of a view is changed layoutSubviews
is called on that view. So instead of letting customTitleView
be a regular UIView
you need to make it a custom view that inherits from UIView
. In that custom view you override layoutSubviews
and in your implementation of layoutSubviews
you make sure everything is aligned the way you want based on the new frame (self.frame
). I'll leave the implementation to you.
精彩评论