Last item in UICollectionView not alligned - Swift

2019-08-04 12:52发布

I have seen some questions similar to this one but none have really helped me. The last item in my collection view is always lower than the other items, as you can see in the image below:

Last Item Unalligned

If I increase the height of the UICollectionView then the last image alligns correctly but there is a huge gap between at the top and bottom of the UICollectionView as seen in the image below:

Last Item Alligned

The sizing of the cells are controlled by this code:

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

    let image =  UIImage(data: imageArray[indexPath.row])

    var size = image?.size
        let height = size!.height
        let width = size!.width
        let imagewidth = (width / height) * 214



    return CGSize(width: imagewidth, height: 214)
}

From what I understand, this should be making the height of each of the images the same, meaning it doesn't matter what the height of the original image is.

I also have another collection view in which the last item is aligned correctly and is set up in the exact same way so I'm a bit confused. What do you think the problem is? I have read that this could be a bug, but is there anyway around it? I am still learning about Swift and programming in general so if you have any other tips for me, they would be massively appreciated.

Thanks

1条回答
可以哭但决不认输i
2楼-- · 2019-08-04 13:28

If there is a huge gap between at the top and bottom of the UICollectionView , you can solve the problem via setting viewController's automaticallyAdjustsScrollViewInsets false.

override func viewDidLoad() {
        super.viewDidLoad()

        //remove the blank of top and bottom in collectionView
        self.automaticallyAdjustsScrollViewInsets = false

    }
查看更多
登录 后发表回答