1

I know how to change the frame of a UILabel on rotation.

My question is, when a UILabel is a subView of another UIView, which is a subview of a paging enabled scrollView, is there a smart way to center the uilabel on rotation?

Consider This:

ScrollView --> 3 x UIView (3 pages) --> Each UIView has a UILabel subview.

In portrait all is fine, on rotate, i'm having to explicitly set the frame of each label.

I've tried adding:

    [myLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin |  UIViewAutoresizingFlexibleRightMargin];

But this is not working, I just want the labels centred in the UIView no matter what the rotation. The UIViews already resize themselves correctly.

I did try to use something along the lines of:

        [myLabel setCenter:CGPointMake(myView.frame.size.width / 2, myView.frame.size.height / 2)];

and placed this in the method: - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration

However this isn't working well, as the UIViews are resized on rotation themselves.

Thanks

1 Answer 1

2

Not sure if the scroll view will affect my answer. But if you just want to center (horizontally) a UILabel inside its superview, the following code will work

-(void)viewDidLoad {
    // Init the label
    // Assume that you want its size to be 100 x 30
    // And its superview is v0
    label.frame = CGRectMake((v0.width - 100) / 2, 10, 100, 30);
    label.autoresizingMask = UIViewAutoresizingMaskFlexibleLeftMargin | UIViewAutoresizingMaskFlexibleRightMargin;
    [v0 addSubview:label];

    // No need of handling rotation explicitly anywhere else
}

Notice the use of v0.width: thought this may be zero at the time the view loads, this method still works. The initial value doesn't matter actually.

If you need to do something special that autoresizingMask can't help, just override layoutSubviews which is invoked when rotation happens. The last solution is to observe frame property of the view (eg if you are not working with a UIViewController and doesn't have layoutSubviews at hand...)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.