den330
den330

Reputation: 403

Bounds and Frame, If a view is Not rotated, is the size of these two property always identical to each other?

I tried to make a view(not rotated) wider in a controller. I tried two approaches to do that:

  1. MyView.frame.size.width += 80
  2. MyView.bounds.size.width += 80

And I noticed that they gave me different effect, how does that happen?

Upvotes: 1

Views: 63

Answers (3)

ilovecomputer
ilovecomputer

Reputation: 4708

According to Apple Doc:

When you set the size value of frame:

When you set the frame property, the size value in the bounds property changes to match the new size of the frame rectangle.

When you set the size value of bounds:

When you set the size of the bounds property, the size value in the frame property changes to match the new size of the bounds rectangle.

So the size of frame and bounds should retain same. However, different effect is possible(like different position) as frame refer to superView's coordinate system but bounds specifies the size of the view (and its content origin) in the view’s own local coordinate system.

Notice: sometimes frame will be considered invalid

If a view’s transform property is not the identity transform, the value of that view’s frame property is undefined and must be ignored. When applying transforms to a view, you must use the view’s bounds and center properties to get the size and position of the view. The frame rectangles of any subviews are still valid because they are relative to the view’s bounds.

Upvotes: 1

Hamish
Hamish

Reputation: 80811

According to the docs on the bounds and frame of a UIView respectively...

bounds:

Changing the bounds size grows or shrinks the view relative to its center point.

frame:

Setting this property changes the point specified by the center property and the size in the bounds rectangle accordingly.

Therefore increasing the bounds width by 80 will add 40pts to the left and right sides of the view, whereas increasing the frame width by 80 will add 80pts to the right hand side of the view.

While you are correct in saying that when the transform is identity, then bounds.size should be the same as frame.size, this doesn't mean that the behaviour when you set these values is the same (which it isn't). I would also take note of what Duncan says about the namings of your variables.

Upvotes: 1

Duncan C
Duncan C

Reputation: 131426

If the transformation matrix is the identity matrix (not just not rotated) then I would expect frame.size and bounds.size to be the same and changing either to have the same effect.

Note that the code you posted won't work in Objective-C. You'd have to write it like this:

CGRect myViewFrame = myView.frame;
myViewFrame.size.width *=2;
myView.frame = myViewFrame;

(also note that I'm following iOS naming conventions and naming myView starting with a lower-case letter. Variables should start with lower-case letters.)

Upvotes: 1

Related Questions