AppsDev
AppsDev

Reputation: 12509

NSTextAlignmentCenter for UILabel not working

I have a view with a UILabel in a separated nib file. I load this nib file within the viewWillAppear: method of an UIViewController, and I'm trying to set the textAlignment property of the UILabel there, this way:

- (void)viewWillAppear:(BOOL)animated
{
   [super viewWillAppear:animated];

   NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:nil options:nil];
        for (UIView *view in views) {
            if([view isKindOfClass:[UIView class]])
            {
                self.customView = (MyView *)view;

                ((MyView *)self.customView).myLabel.textAlignment = NSTextAlignmentCenter;

                ((MyView *)self.customView).myLabel.text = @"My text";
                [((MyView *)self.customView).myLabel sizeToFit];

                [self.view addSubview:self.customView];
            }
        }
}

But when I run the app, the text is not centered, even if I set the alignment in the nib (I can see the text centered in Xcode's IB). This is an app for iOS 7+ and I'm using Xcode 6.1.1. Why could this be not working?

Thanks

Upvotes: 2

Views: 4646

Answers (5)

Johnny Rockex
Johnny Rockex

Reputation: 4196

For UILabels with NSTextAlignmentCenter, you can center the label afterwards like this:

float w = self.view.frame.size.width;

title.text = @"What do you want to say?";

[title sizeToFit];

title.frame = CGRectMake((w-title.frame.size.width)/2, title.frame.origin.y, title.frame.size.width, title.frame.size.height);

Upvotes: 2

Horatio
Horatio

Reputation: 1871

Write this line of code

((MyView *)self.customView).myLabel.textAlignment = NSTextAlignmentCenter;

after this one

[self.view addSubview:self.customView];

Upvotes: 0

Chandan kumar
Chandan kumar

Reputation: 1084

  [((MyView *)self.customView).myLabel sizeToFit];

remove this line...

Upvotes: 0

ABC
ABC

Reputation: 718

You are calling [((MyView *)self.customView).myLabel sizeToFit]; and from the docs sizeToFit "Resizes and moves the receiver view so it just encloses its subviews.".

You shouldn't be able to center text in a UILabel if the text fills the label.

Try to remove this method call and see what happens.

Upvotes: 2

KIDdAe
KIDdAe

Reputation: 2722

I guess the problem is coming from :

[((MyView *)self.customView).myLabel sizeToFit];

Centering does not change the frame.origin.x of your label. But if you apply sizeToFit afterwards, all content will be centered in a smaller zone (without changing the x offset) and will get the feeling that it's not centered anymore.

Upvotes: 4

Related Questions