Peter Wang
Peter Wang

Reputation: 1838

Dynamic Layout iOS with Collection View

This might be a simple question -- I'm new to iOS Development.

I have a homepage with a Collection View with four cells that take up the whole screen (top left, top right, bottom left, bottom right) in portrait mode. In landscape mode, I want all four cells to be side by side in a row.

Is Collection View the right layout to use? Should I use Autoresizing to do this, or do I have to use some other layout constraints?

Thank you!

Upvotes: 1

Views: 524

Answers (2)

wskcoder
wskcoder

Reputation: 276

it should be a merge beetween UIStackView and Sizeclasses

you will need to use 3 stackviews

the stackviews have to have fill equaly distribution.

enter image description here

the selected stackview has to have axis vertical by default, but you should add horizontal axis sizeclass width regular | height any

Upvotes: 0

sarosh mirza
sarosh mirza

Reputation: 702

UICollectionView is the right layout to use. you can use the following for making layout

    func collectionView(collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
    let totalSpace = flowLayout.sectionInset.left
        + flowLayout.sectionInset.right
        + (flowLayout.minimumInteritemSpacing * CGFloat(4 - 1))
    let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(4))
    return CGSize(width: size, height: size)
}

Following way you can use it inside your view controller

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

@objc(collectionView:layout:sizeForItemAtIndexPath:)
func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAt indexPath: IndexPath) -> CGSize {

    let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
    let totalSpace = flowLayout.sectionInset.left
        + flowLayout.sectionInset.right
        + (flowLayout.minimumInteritemSpacing * CGFloat(4 - 1))
    let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(4))
    return CGSize(width: size, height: size)
}
}

Upvotes: 1

Related Questions