更改视图边界会影响框架

时间:2015-10-16 02:07:27

标签: ios uiview frame cgrect bounds

我正在尝试了解视图如何响应其更改的边界。如果我更改视图的边界原点,它会相应地更改帧原点吗?

E.g。

UIView *greenView = [[UIView alloc] initWithFrame:CGRectMake(150, 150, 150, 200)];
greenView.backgroundColor = [UIColor colorWithRed:0.494 green:0.827
                                             blue:0.129 alpha:1];
[self.view addSubview:greenView];
greenView.bounds = CGRectMake(0, 150, greenView.bounds.size.width, greenView.bounds.size.height);

这不会将画面的原点改为(150,300)吗?运行上面的代码似乎没有改变它的框架。 (我知道你并不打算用界限来改变观点位置,这只是一个假设)。

1 个答案:

答案 0 :(得分:7)

Per Apple Documentation,这是视图的框架,边界和中心之间的关系:

  

虽然您可以更改框架,边界和中心属性   独立于其他属性,对一个属性的更改会影响其他属性   通过以下方式:

     
      
  • 设置frame属性时,bounds属性中的size值会更改以匹配框架矩形的新大小。该
      中心属性中的值类似地更改以匹配新的属性   框架矩形的中心点。
  •   
  • 设置center属性时,框架中的原点值会相应更改。
  •   
  • 设置bounds属性的大小时,frame属性中的size值会更改为与bounds矩形的新大小匹配。
  •   

所以,回答你的问题,改变View的边界上的X,Y位置不应该影响帧。大多数情况下的边界以(0,0)开头。将高度或宽度更改为负值将允许边界的原点变为负值。

编辑:要回答OP问题 - 否,更改边界的位置不会以任何方式影响帧。由于边界是参考视图自己的坐标系,因此在自协调系统中改变X,Y不会改变superview坐标系中的位置。

您可以尝试使用两个自定义视图:

UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake(50.0f, 100.0f, 150.0f, 150.0f)];
view1.backgroundColor = [UIColor redColor];

NSLog(@"view1.bounds = %@", NSStringFromCGRect(view1.bounds));
NSLog(@"view1.frame = %@", NSStringFromCGRect(view1.frame));

UIView* view2 = [[UIView alloc] initWithFrame:CGRectInset(view1.bounds, 20.0f, 20.0f)];
view2.backgroundColor = [UIColor yellowColor];

NSLog(@"view2.bounds = %@", NSStringFromCGRect(view2.bounds));
NSLog(@"view2.frame = %@", NSStringFromCGRect(view2.frame));

NSLog(@"view1.bounds = %@", NSStringFromCGRect(view1.bounds));
NSLog(@"view1.frame = %@", NSStringFromCGRect(view1.frame));

NSLog(@"view2.bounds = %@", NSStringFromCGRect(view2.bounds));
NSLog(@"view2.frame = %@", NSStringFromCGRect(view2.frame));

[view1 addSubview:view2];

然后更改像这样绑定的子视图:

CGRect frame = view2.bounds;
frame.origin.x += 20.0f;
frame.origin.y += 20.0f;
view2.bounds = frame;

更改边界根本不会影响帧。两个视图在屏幕上看起来都一样:

enter image description here enter image description here

最后,尝试更改父视图的边界以查看以下屏幕:

CGRect frame = view1.bounds;
frame.origin.x += 20.0f;
frame.origin.y += 20.0f;
view1.bounds = frame;

enter image description here