Kamanda
Kamanda

Reputation: 305

How to correctly use aspect ratio in swift xcode storyboard?

I've been scratching my head about this all day. I am try to have the iphone 6s reflect what the iphone 12 is showing. I'm not good at autolayout but I'd just like an idea or a point in the right direction so I can make it look like its counterpart. All help is appreciated.

enter image description here

(P.S I'm using storyboard and have never tried to do it programmatically.)

All help is appreciated.

Upvotes: 0

Views: 2752

Answers (2)

DonMag
DonMag

Reputation: 77462

The general idea...

  • use a Vertical Stack View holding 3 "rows" of Horizontal Stack Views
  • each Horizontal stack view holds two "tile" UIViews
  • set Alignment: Fill, Distribution: Fill Equally and Spacing: 0 on all the stack views
  • give the first view (in this image, the red view) an Aspect Ratio constraint ... from your image, it looks like you want 3:2.5
  • embed the stack view in a "container" UIView - I called it GridView
  • constrain the stack view >= 12 on all 4 sides
  • also constrain the stack view = 12 on all 4 sides, but give those constraints Priority: High (750) ... this will cause auto-layout to "pull" the stack view to the edges, but allow it to be narrower if needed
  • then we also give the stack view Center Vertical and Horizontal constraints
  • constrain GridView to Zero Leading, Trailing and Bottom

That will give you 6 tiles that will maintain their aspect-ratios based on device size, and it will center the vertical stack view if needed:

enter image description here

The next step would be to embed a "rounded corner bordered" view in each "tile" view, constraining it at 8-pts on all 4 sides (less or more to get your desired "spacing"):

enter image description here

Here's the result on an iPhone 12 and iPhone 6s:

enter image description here

As you can see, there is less vertical space between the labels and the banner and grid views, and there is slightly more horizontal space on the sides of the stack view.

Here's a link to the Storyboard source and class files I used for this, so you can try it out and inspect the elements. I used just enough to demonstrate. You would probably want to make a custom "tile" view class that would contain the rounded corner bordered view and label:

https://gist.github.com/DonMag/8a0b2d85bbbb4262e43d73e745826ee5

Upvotes: 2

hamza-faroooq
hamza-faroooq

Reputation: 19

It's all the game of constraints if you want to handle this using story board.

There are multiple ways to achieve this UI. Either you can use UICollectionView and use UICollectionViewCells to show 2 cells in each column to manage the data or you can use UIStackView to manage your UI easily.

If you want square shapes, then you must use UIScrollView as the UI can exceed Screen Height. If not, just put your view in UIStackView and let it handle some of your UI constraints itself.

Upvotes: 0

Related Questions