1

如果我有 asuperview.frame = CGRectMake(0,0,200,200);和 a subview.frame = CGRectMake(0,0,100,100),子视图具有灵活的宽度和高度,我认为当 superview 的框架更改为 时(0,0,150,150),子视图的框架应该更改为(0, 0, 75, 75). 但事实并非如此。

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

UIView * view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
view1.backgroundColor = [UIColor blackColor];
[self.view addSubview:view1];

UIView * view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
view2.backgroundColor = [UIColor redColor];
view2.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin;
[view1 addSubview:view2];

view1.frame = CGRectMake(0, 0, 150, 150);
[self printRect:view2.frame];
}

- (void) printRect:(CGRect)rect
{
NSLog(@"%0.1f, %0.1f, %0.1f, %0.1f", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
}

输出:

0.0, 0.0, 50.0, 50.0

而当superview的frame变为(0,0,100,100)时,subview的frame会变为(0,0,0,0)

为什么..

4

2 回答 2

2

用我的代码替换你的代码行,因为你忘记UIViewAutoresizingFlexibleBottomMarginUIViewAutoresizingFlexibleTopMargin

  view2.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;
于 2012-10-30T10:18:23.427 回答
0

在你的代码中,有固定的边距,从上顺时针到左边是( 0、100、100、0 view2),这解释了你的自动调整大小的行为。view2只有放大时,您view2的高度和宽度才会改变view1。所以你应该在你的 autoresziing 掩码中添加UIViewAutoresizingFlexibleBottomMarginandUIViewAutoresizingFlexibleTopMarginview2

于 2012-10-30T10:31:58.323 回答