UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

What’s the difference between frame and bounds?

Swift version: 5.6

Paul Hudson    @twostraws   

All UIView subclasses have two properties that at first glance seem similar: frame and bounds. Both return a CGRect – a rectangle containing their X and Y position, plus their width and height – but that doesn’t mean they are the same.

At its simplest, a view’s bounds refers to its coordinates relative to its own space (as if the rest of your view hierarchy didn’t exist), whereas its frame refers to its coordinates relative to its parent’s space.

This means a few things:

  1. If you create a view at X:0, Y:0, width:100, height:100, its frame and bounds are the same.
  2. If you move that view to X:100, its frame will reflect that change but its bounds will not. Remember, the bounds is relative to the view’s own space, and internally to the view nothing has changed.
  3. If you transform the view, e.g. rotating it or scaling it up, the frame will change to reflect that, but the bounds still won’t – as far as the view is concerned internally, it hasn’t changed.

When you change the width or height of either frame or bounds, the other value is updated to match. Generally it’s better to modify bounds plus center and transform, and let UIKit calculate the frame for you.

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 2.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.7/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.