首页 > 解决方案 > UIViewAutoresizingMask 将子视图宽度扩展到父视图之外

问题描述

我需要向一些人展示它在 Autolayout 之前的样子,所以我想尝试自动调整遮罩大小来构建一个如下所示的视图:

 ————————————
|  ————————  |
| |  red   | |
| |        | |
|  ————————  |
|            |
|   yellow   |
 ————————————

我希望红色 UIView 水平扩展,但在设备旋转时将其左侧、顶部和右侧边距保持在 20 点。

这是我的代码:

// .h

@interface NextViewController : UIViewController

@end

// .m

@interface NextViewController ()

@property (nonatomic) UIView *rectView;

@end

@implementation NextViewController

- (void)loadView {
    self.view = [[UIView alloc] initWithFrame:CGRectZero];
    self.view.backgroundColor = [UIColor yellowColor];

    // 280 width for iPhone 5S when left and right paddings are 20 points
    self.rectView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 280, 100)];
    [self.view addSubview:self.rectView];
    self.rectView.backgroundColor = [UIColor redColor];
    self.rectView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
}

@end

我的问题是红色 UIView 总是超出黄色 UIView 的宽度:

在此处输入图像描述

我打印了红色视图的描述:

Printing description of $15:
<UIView: 0x7fc360e181c0; frame = (20 20; 600 100); autoresize = W; layer = <CALayer: 0x600000226960>>

那么我做错了什么?

标签: iosobjective-ccocoa-touchuikit

解决方案


啊,我现在明白了。就是这一行:

self.view = [[UIView alloc] initWithFrame:CGRectZero];

子视图的自动调整大小掩码正在CGRectZero根据顶层视图的这个框架进行评估,这就是它们没有正确调整大小的原因。我在纵向模式下给了它一个 iPhone 5S 屏幕的框架,并修复了旋转缩放:

self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];

推荐阅读