iosswiftuicollectionviewuicollectionviewflowlayoutiphone-8

How to show two items in one row? with using uicollectionView


I followed this video for study Collection View (https://www.youtube.com/watch?v=jQ8EUsQZJ5g)

And I wrote code like this :

if ( CollectionViewFlowLayout == nil ){
        let numberOfItemsForRow : CGFloat = 2
        let UpDownSpace : CGFloat = 5
        let LeftRightSpace : CGFloat = 5

        //CollectionViewFlowLayout은 delgate 처럼 소재지를 수정하고 꾸밀 수 있는 것이다.
        CollectionViewFlowLayout = UICollectionViewFlowLayout()
        //이건 margin의 크기를 정해주는 것이다.
        CollectionViewFlowLayout?.sectionInset = UIEdgeInsets.zero
        //이건 화면을 수직으로 내릴 것이냐, 수평으로 스크롤 할것이냐를 정해준다.
        CollectionViewFlowLayout?.scrollDirection = .vertical
        //소재지의 위 아래의 간격을 정해준다.
        CollectionViewFlowLayout?.minimumLineSpacing = UpDownSpace
        //같은 줄에 있는 소재지의 오른쪽 왼쪽 사이의 간격을 정해준다.
        CollectionViewFlowLayout?.minimumInteritemSpacing = LeftRightSpace


        let total = (LeftRightSpace * (numberOfItemsForRow - 1))

        let width = (CollectionView.frame.width - total) / numberOfItemsForRow

        let height = width

        //itemsize : 소재지의 크기를 정 할 수 있다
        CollectionViewFlowLayout?.itemSize = CGSize(width: width, height: height)


        CollectionView.setCollectionViewLayout(CollectionViewFlowLayout!, animated: true)


    }

But when I use simulator with iPhone 8, It make error

Other things are Good! without iPhone 8

enter image description here


Solution

  • I think your total should be calculated as:

    let total = LeftRightSpace * (numberOfItemsForRow + 1), because you are taking away left, right and interitem spacing.

    Or try calculating width as:

    let width = (UIScreen.main.bounds.width - total) / numberOfItemsForRow