UIView和它的子类都有frame和bounds属性。有什么不同?


当前回答

让我加上我的5美分。

视图的父视图使用Frame将其放置在父视图中。

视图本身使用Bounds来放置它自己的内容(就像滚动视图在滚动时所做的那样)。请参见clipsToBounds。边界也可以用来放大/缩小视图的内容。

类比: 框架~电视屏幕 边界~相机(缩放,移动,旋转)

其他回答

框架与边界

If you create a view at X:0, Y:0, width:400, height:400, its frame and bounds are the same. If you move that view to X:400, its frame will reflect that change but its bounds will not. Remember, the bounds is relative to the view’s own space, and internally to the view nothing has changed. If you transform the view, e.g. rotating it or scaling it up, the frame will change to reflect that, but the bounds still won’t – as far as the view is concerned internally, it hasn’t changed. If you change the bounds then it will change the content inside the frame because the origin of the bounds rectangle starts at a different part of the view.

试着运行下面的代码

- (void)viewDidLoad {
    [super viewDidLoad];
    UIWindow *w = [[UIApplication sharedApplication] keyWindow];
    UIView *v = [w.subviews objectAtIndex:0];

    NSLog(@"%@", NSStringFromCGRect(v.frame));
    NSLog(@"%@", NSStringFromCGRect(v.bounds));
}

这段代码的输出是:

机箱设备方向为纵向

{{0, 0}, {768, 1024}}
{{0, 0}, {768, 1024}}

机箱设备方向为横向

{{0, 0}, {768, 1024}}
{{0, 0}, {1024, 768}}

显然,你可以看到框架和边界之间的区别

UIView的边界是一个矩形,表示为相对于它自己的坐标系(0,0)的位置(x,y)和大小(宽度,高度)。

UIView的框架是一个矩形,表示为相对于它所包含的父视图的位置(x,y)和大小(宽度,高度)。

因此,想象一个视图的大小为100x100(宽x高),位于其父视图的25,25 (x,y)处。下面的代码打印出这个视图的边界和框架:

// This method is in the view controller of the superview
- (void)viewDidLoad {
    [super viewDidLoad];

    NSLog(@"bounds.origin.x: %f", label.bounds.origin.x);
    NSLog(@"bounds.origin.y: %f", label.bounds.origin.y);
    NSLog(@"bounds.size.width: %f", label.bounds.size.width);
    NSLog(@"bounds.size.height: %f", label.bounds.size.height);

    NSLog(@"frame.origin.x: %f", label.frame.origin.x);
    NSLog(@"frame.origin.y: %f", label.frame.origin.y);
    NSLog(@"frame.size.width: %f", label.frame.size.width);
    NSLog(@"frame.size.height: %f", label.frame.size.height);
}

这段代码的输出是:

bounds.origin.x: 0
bounds.origin.y: 0
bounds.size.width: 100
bounds.size.height: 100

frame.origin.x: 25
frame.origin.y: 25
frame.size.width: 100
frame.size.height: 100

我们可以看到,在这两种情况下,视图的宽度和高度是相同的不管我们是在看边界还是在看框架。不同之处在于视图的x,y定位。在边界的情况下,x和y坐标是0,0,因为这些坐标是相对于视图本身的。然而,坐标系x和y坐标是相对于视图在父视图中的位置(前面我们说过是在25,25)。

还有一个关于UIViews的很棒的演示。请看幻灯片1-20,它不仅解释了帧和边界之间的区别,而且还展示了可视化的例子。

Frame相对于SuperView,而Bounds相对于NSView。

例子:40 X = Y = 60。也包含3个视图。这张图向你展示了清楚的想法。

让我加上我的5美分。

视图的父视图使用Frame将其放置在父视图中。

视图本身使用Bounds来放置它自己的内容(就像滚动视图在滚动时所做的那样)。请参见clipsToBounds。边界也可以用来放大/缩小视图的内容。

类比: 框架~电视屏幕 边界~相机(缩放,移动,旋转)