Uiview bounds Vs frame in iOS swift

 

This tutorial is updated for X code 7.3 & swift 2.2

I learned what frame & bounds in beginning but I didn’t write it down in my cheat sheet. Now every time I come across frame and bounds I pretend I know what it is and move along. Because I was too lazy to go back to learn exactly what it is. But enough is enough now I will create cheat diagram here. So you will know what is frame & bounds by just looking at it once.

Frame of uiview is actually co-ordinate with respect to its super view. To remember frame think of it as picture frame as illustrated in the image. As you can see there is inner view inside main view. And there is image view with image of actress Eva Green. Frame of inner view with respect to main view as its super view is (0,0).

frame-zero

When you move the frame of uiview it also moves everything inside inner view. As you can see in the image the image view is also moved along with inner view.

frame-50

You can access frame value by writing innerView.frame.origin.x & innerView.frame.origin.y
All frame values are in CGFloat. So if you may have to convert to Int to display on label or convert Int to CGFloat to change frame.

Bounds of uiview are its own co-ordinate system. Bounds are unaware of its super view. As you can see in the image at initial state uiviews bounds are zero.

bounds-zero

When you change bounds of uiview then it redraws the content inside inner view from different starting point. By default inner view will not clip the part of image view outside inner view. But I am showing this to understand the concept easily.

bounds-50

You can access bounds value by writing innerView.bounds.origin.x & innerView.bounds.origin.y
Just like frame bounds values are also in CGFloat. And you can also use negative values for frame and bounds.

Challenge 1: Create an app to show difference between bounds & frame using uislider.
You can see my uislider tutorial for reference.
You can download image of Eva Green here.

frame x & bounds x
Download Challenge 1 Solution
Challenge 2 : Show both x & y values using uislider

frame x,y & bounds x,y
Download Challenge 2 Solution

Total 0 Votes
0

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?