iOS Frame vs Bounds

2017-12-16  本文已影响0人  逗比喵喵

According to official iOS Documentation about UIView, Frame and Bounds. We could make a cheatsheet below:

There is also another saying on internet - bounds is where the subviews are allowed to draw with respect to itself. But it is true only if clipsToBounds is set to TRUE.

In fact, frame, bounds and also center, they are interlocked. Setting one property changes the others in the mean time. Changing the size portion of bounds grows or shrinks the view relative to its center point. Changing the size also changes the size of the rectangle in the frame property to match.

Example

Below is an example to show how bounds effect a view's superview and subview

image.png
// 父 View
let superview: UIView = UIView(frame: CGRect(x: 100, y: 100, width: 200, height: 200))
superview.backgroundColor = .yellow
        
// 子 View
let childview: UIView = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
childview.backgroundColor = .red
        
// 子 View 的 子 View
let childchildview: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
childchildview.backgroundColor = .green
        
self.view.addSubview(superview)
superview.addSubview(childview)
childview.addSubview(childchildview)
        
// 打印信息
print("superview")
print(superview.frame)  // (100.0, 100.0, 200.0, 200.0)
print(superview.bounds) // (0.0, 0.0, 200.0, 200.0)
print("childview")
print(childview.frame)  // (50.0, 50.0, 100.0, 100.0)
print(childview.bounds) // (0.0, 0.0, 100.0, 100.0)
print("childchildview")
print(childchildview.frame)  // (0.0, 0.0, 50.0, 50.0)
print(childchildview.bounds) // (0.0, 0.0, 50.0, 50.0)

If now we change the origin point of childview's bounds:

childview.bounds = CGRect(x: 100, y: 100, width: 100, height: 100)

So what would happen here is the coordinate system of childview changes. It has no bussiness with its superview but only effects its subview (the "childchildview"). Let's draw below the NEW coordinate system of childview:

new_coordinate_system.png

Next, let's set clipsToBounds to true:

childview.clipsToBounds = true

So now, the childchildview is not visible anymore. From now on, we could say bounds is where the subviews are allowed to draw with respect to itself with clipsToBounds set to true.

上一篇 下一篇

猜你喜欢

热点阅读