简体   繁体   中英

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.

在此处输入图像描述

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

All help is appreciated.

The general idea...

  • use a Vertical Stack View holding 3 "rows" of Horizontal Stack Views
  • each Horizontal stack view holds two "tile" UIView s
  • 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:

在此处输入图像描述

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"):

在此处输入图像描述

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

在此处输入图像描述

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM