简体   繁体   中英

Swift: collectionView cell

I create collectionView And I have 3 cells. I want to that my cells look like this for all screens in all device:

在此处输入图片说明

But I have this result for iPad.

在此处输入图片说明

How to fix it?

Update

I add collectionView in UIViewController . I have this constraints for collectionView :

在此处输入图片说明

Sizing my cells:

在此处输入图片说明

code:

func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 4
    }

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

        return 3
    }

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let itemsPerRow: CGFloat = 3
    let itemWidth = (collectionView.bounds.width / itemsPerRow)
    let itemHeight = itemWidth * 1.5
    return CGSize(width: itemWidth, height: itemHeight)
}

You need to change the cell size adaptively, otherwise the size will not work for all screen sizes.

You have your function, where you return the cell size:

return CGSize(width: 182, height: 275)

Instead, make it adaptive like this:

return CGSize(width: self.view.frame.width / 3, height: self.view.frame.height)

Or, to have the gap in-between, create an offset:

let offset = 10

let width = self.view.frame.width - offset * 4 // 4 gaps
let height = self.view.frame.height - offset * 2 // 2 gaps

return CGSize(width: width / 3, height: height) // Divide into equally-sized cells

Of course, the self.view can be replaced with any container you want the cells to fit in.

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