问题
What is an optimal way to create a grid view for iOS with two columns per row as shown in the screenshot?
I am currently using tableview with static cells, but the UI gets distorted on some iPad. Also how best to arrange the grid border? Currently I use imageview of center ones, and a new cell for the horizontal ones with an imageview. But this does not feel right.
回答1:
That should be made with an UICollectionView
, it has a specific delegate which is UICollectionViewDelegateFlowLayout
that makes it very easy to reach that appearance.
Step 1
Add UICollectionViewDelegateFlowLayout
in your UIViewController
, like: <#Your View Controller#> : UICollectionViewDelegateFlowLayout
Step 2
The amount of cells per row is calculated based on the amount of cells that fit the UICollectionView width. Therefore, having cells with half the width will fit 2 cells per row.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width / 2, height: /* your desired height here */)
}
Tips:
You can even make it a little smaller than half the screen, by multiplying values like this: (collectionView.frame.width / 2) * 0.98
, you can also subtract constant values.
You may need to set collectionView.minimumInteritemSpacing = 0
since this attribute default value is 10.0
Documentation: UICollectionViewFlowLayout
回答2:
This looks like a job for a UICollectionView! (It shouldn't be too hard to change your UITableViewDataSource protocol methods to their UICollectionViewDataSource equivalents.)
来源:https://stackoverflow.com/questions/54732195/what-layout-is-better-for-a-ui-with-two-card-cells-per-row