What is the difference between 'Frame' and 'Bounds' in iOS development?

Instruction: Explain the concepts of 'Frame' and 'Bounds' in the context of UIViews in iOS.

Context: Understanding the distinction between 'Frame' and 'Bounds' is fundamental for iOS developers, as it directly impacts the layout and positioning of UI components. This question tests the candidate's knowledge of UIView properties and their ability to effectively manage user interfaces in iOS apps.

Updated

Official answer

A UIView's frame describes its rectangle in its superview's coordinate system. Its bounds describes its rectangle in its own local coordinate system. Both use points, not necessarily physical pixels.

With an identity transform, a view whose frame is (x: 20, y: 30, width: 100, height: 50) normally begins with bounds (x: 0, y: 0, width: 100, height: 50) and center (70, 55). Moving its frame origin moves the view within the superview. Changing its bounds origin instead changes the local coordinate mapping; it does not move the outer rectangle in that simple case, which is useful for reasoning about scrolling.

Changing bounds size is not independent of frame size. With the identity transform, setting bounds size to 200 by 50 while preserving center makes the frame origin (-30, 30) and its size 200 by 50. Content rendering and subview layout then depend on layout constraints, autoresizing and contentMode; resizing does not universally mean scaling every drawing or subview.

If transform is not the identity, UIKit documents frame as undefined for this purpose. Position and size the transformed view using center and bounds instead of treating frame as a reliable input. With Auto Layout, update the relevant constraints and let layout determine geometry; manually setting frame may be overwritten by the next layout pass.

UIView frame contract, UIView bounds contract

Related Questions