简体   繁体   中英

Center align single collectionview cell

I like to center align a UICollectionview cell, if only single cell is returned. I am using this

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        if self.imageSelected.count == 1
        {
            func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
                return UIEdgeInsetsMake(0, 100, 0, 0)
            }
        }

        return self.imageSelected.count

    }

The above code is getting selected if the count is one but I am not seeing any movement in the cell location.

I also tried this but here it is not even hitting the breakpoint

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        if self.imageSelected.count == 1 {
            return UIEdgeInsetsMake(0, 100, 0, 0)
        } else {
            return UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return self.imageSelected.count

    }

Put this into your view controller instead of the code in your question:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    if self.imageSelected.count == 1 {
        return UIEdgeInsetsMake(0, 100, 0, 0)
    } else {
        return UIEdgeInsetsMake(0, 0, 0, 0)
    }
}

This makes the code that you have created work. If you need a more exact answer on how to center a cell, please ask and I will put some time and effort into helping you out :)

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