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


当前回答

框架是一个矩形,它定义了UIView相对于它的父视图。

bounds rect是定义NSView坐标系的值的范围。

也就是说,这个矩形中的任何东西都会显示在UIView中。

其他回答

这里有一个很棒的视频(来自Sean Allen):

Swift - Bounds vs. Frame - iOS面试问题

框架是相对于父视图坐标的位置:

边界是相对于自身坐标系的位置。

和…如果视图是旋转的,它会变得更加棘手。(看视频!)

框架与边界

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.

以上所有答案都是正确的,以下是我的看法:

为了区分框架和边界概念,开发者应该阅读:

相对于父视图(父视图),它包含在= FRAME中 相对于它自己的坐标系,决定了它的子视图location = BOUNDS

"bounds"是令人困惑的,因为它给人的印象是坐标是它所设置的视图的位置。但这些是有关系的,可以根据坐标系常数进行调整。

上面的答案已经很好地解释了边界和框架之间的区别。

边界:一个视图的大小和位置按照它自己的坐标系统。 Frame:相对于它的SuperView的视图大小和位置。

然后有一个混乱的情况下,边界的X,Y将永远是“0”。这是不对的。这也可以在UIScrollView和UICollectionView中理解。

当边界' x, y不为0时。 假设我们有一个UIScrollView。我们实现了分页。UIScrollView有3个页面,它的ContentSize的宽度是屏幕宽度的3倍(假设屏幕宽度是320)。高度是常数(假设200)。

scrollView.contentSize = CGSize(x:320*3, y : 200)

添加三个UIImageViews作为子视图,并密切关注frame的x值

let imageView0 = UIImageView.init(frame: CGRect(x:0, y: 0 , width : scrollView.frame.size.width, height : scrollView.frame.size.height))
let imageView1 :  UIImageView.init( frame: CGRect(x:320, y: 0 , width : scrollView.frame.size.width, height : scrollView.frame.size.height))
let imageView2 :  UIImageView.init(frame: CGRect(x:640, y: 0 , width : scrollView.frame.size.width, height : scrollView.frame.size.height))
scrollView.addSubview(imageView0)
scrollView.addSubview(imageView0)
scrollView.addSubview(imageView0)

0页: 当ScrollView为0时,Page的边界将为 (x:0,y:0,宽:320,高:200) 第1页: 滚动并移动到第1页。 现在边界将是(x:320,y:0,宽度:320,高度:200) 记住我们说过在它自己的坐标系中。现在我们ScrollView的可见部分的x值是320。看看imageView1的帧。 第2页: 滚动并移动到第2页 边界:(x:640,y:0,宽:320,高:200) 再看一下imageView2的帧

UICollectionView的情况也一样。查看collectionView最简单的方法是滚动它并打印/记录它的边界,您将了解它的概念。

试着运行下面的代码

- (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}}

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