1

知道如何在旋转时更改 UILabel 的框架。

我的问题是,当 UILabel 是另一个 UIView 的子视图时,它是启用分页的滚动视图的子视图,是否有一种聪明的方法可以使 uilabel 居中旋转?

考虑一下:

ScrollView --> 3 x UIView (3 pages) --> 每个 UIView 都有一个 UILabel 子视图。

在纵向一切都很好,在旋转时,我必须明确设置每个标签的框架。

我试过添加:

    [myLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin |  UIViewAutoresizingFlexibleRightMargin];

但这不起作用,我只希望标签在 UIView 中居中,无论旋转如何。UIViews 已经正确地调整了自己的大小。

我确实尝试使用以下内容:

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

并将其放在方法中: - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration

然而,这并不好,因为 UIViews 在旋转时会自行调整大小。

谢谢

4

1 回答 1

2

不确定滚动视图是否会影响我的回答。但是,如果您只想将 UILabel 居中(水平)在其超级视图中,则以下代码将起作用

-(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
}

注意使用v0.width: 认为在视图加载时这可能为零,但此方法仍然有效。初始值实际上并不重要。

如果您需要做一些autoresizingMask无济于事的特殊事情,只需覆盖layoutSubviews在旋转发生时调用的内容。最后一个解决方案是观察frame视图的属性(例如,如果您没有使用 UIViewController 并且layoutSubviews手头没有......)

于 2013-06-22T15:17:25.410 回答