当前位置 : 主页 > 手机开发 > ios >

ios – 更改视图边界会影响框架

来源:互联网 收集:自由互联 发布时间:2021-06-11
我试图了解一个视图如何响应它的边界被改变.如果我更改视图的边界原点,它会相应地更改帧原点吗? 例如. UIView *greenView = [[UIView alloc] initWithFrame:CGRectMake(150, 150, 150, 200)];greenView.backg
我试图了解一个视图如何响应它的边界被改变.如果我更改视图的边界原点,它会相应地更改帧原点吗?

例如.

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)吗?运行上面的代码似乎没有改变它的框架. (我知道你不是要用边界改变观点位置,这只是一个假设).

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

Although you can change the frame, bounds, and center properties
independent of the others, changes to one property affect the others
in the following ways:

  • When you set the frame property, the size value in the bounds property changes to match the new size of the frame rectangle. The
    value in the center property similarly changes to match the new
    center point of the frame rectangle.
  • When you set the center property, the origin value in the frame changes accordingly.
  • When you set the size of the bounds property, the size value in the frame property changes to match the new size of the bounds rectangle.

所以,回答你的问题,改变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

网友评论