Cocoa: What's the difference between the frame and the bounds?

后端 未结 11 2239
温柔的废话
温柔的废话 2020-11-22 08:00

UIView and its subclasses all have the properties frame and bounds. What\'s the difference?

11条回答
  •  北海茫月
    2020-11-22 08:34

    The answers above have very well explained the difference between Bounds and Frames.

    Bounds : A view Size and Location as per its own coordinate system.

    Frame : A view size and Location relative to its SuperView.

    Then there is confusion that in case of Bounds the X,Y will always be "0". This is not true. This can be understood in UIScrollView and UICollectionView as well.

    When bounds' x, y are not 0.
    Let's assume we have a UIScrollView. We have implemented pagination. The UIScrollView has 3 pages and its ContentSize's width is three times Screen Width (assume ScreenWidth is 320). The height is constant (assume 200).

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

    Add three UIImageViews as subViews and keep a close look at the x value of frame

    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)
    
    1. Page 0: When the ScrollView is at 0 Page the Bounds will be (x:0,y:0, width : 320, height : 200)

    2. Page 1: Scroll and move to Page 1.
      Now the bounds will be (x:320,y:0, width : 320, height : 200) Remember we said with respect to its own coordinate System. So now the "Visible Part" of our ScrollView has its "x" at 320. Look at the frame of imageView1.

    3. Page 2: Scroll and move to Page 2 Bounds : (x:640,y:0, width : 320, height : 200) Again take a look at frame of imageView2

    Same for the case of UICollectionView. The easiest way to look at collectionView is to scroll it and print/log its bounds and you will get the idea.

提交回复
热议问题