简体   繁体   中英

UIView's bounds size vs frame size

Can a frame's size be different from the bound's size of a UIView.

Whenever I set either of them, I notice that both change and they are always in sync. Is there an edge case where this is not true?

Yes; for example, a transformed (eg rotated) view has a different (and useless) frame size.

The frame is purely a convenience, and you could live entirely without it if you had to; the bounds size and center, together, accurately and always describe the view's position and size.

Yes, Please refer the below simple difference between frame and bound:-

The frame of a view is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.

The bounds of a view is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system.

bounds "describes the view's location and size in its own coordinate system".

frame "defines the origin and dimensions of the view in the coordinate system of its superview".

So the two should differ for any view that uses a different coordinate system than its parent. The key giveaway is:

However, if the transform property contains a non-identity transform, the value of the frame property is undefined and should not be modified. In that case, you can reposition the view using the center property and adjust the size using the bounds property instead.

So that's an example Apple gives you of when frame is defined not to have a predictable relationship to bounds : whenever you've set a non-identity transform.

(source for all quotes was the UIView documentation )

They are different.

Assume I have a label:

label.frame = CGRect(x: 0, y: 0, width: 200, height: 20)

Its current frame & bounds ( print(label.frame, label2.bounds) ) are as follows:
(0.0, 0.0, 200.0, 20.0) (0.0, 0.0, 200.0, 20.0)

Note they are currently the same. It is shown in x-position, y-position, width, height (in that order).

Now I will apply a scale Y of 2 to the label like so:

label.transform = CGAffineTransform(scaleX: 1, y: 2)

Its new frame & bounds are as follows:

(0.0, -10.0, 200.0, 40.0) (0.0, 0.0, 200.0, 20.0)

Notice how its own bounds are still the same, while the frame has changed (height went from 20 to 40, and the y-position has shifted by 10 upwards to compensate for the 20 increase so it will remain centred).

This corresponds to what other answers/documentation are saying. Neither are useless, use it accordingly to your needs.

7 years late to the party but hope this still helps others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM