要在UICollectionView中为每个Cell设置不同的高度,可以通过实现UICollectionViewDelegateFlowLayout协议的sizeForItemAt方法来实现。\n\n首先,确保你的类已经遵循了UICollectionViewDelegateFlowLayout协议:\n\nswift\nclass YourViewController: UIViewController, UICollectionViewDelegateFlowLayout {\n // ...\n}\n\n\n然后,实现sizeForItemAt方法来返回每个Cell的大小。在这个方法中,你可以根据Cell的索引或其他条件来计算出不同的高度,并返回给collectionView:\n\nswift\nfunc collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {\n // 根据indexPath或其他条件计算出不同的高度\n let height = // 计算出的高度\n\n // 返回计算出的Cell大小\n return CGSize(width: collectionView.bounds.width, height: height)\n}\n\n\n在这个方法中,你可以根据需要计算出每个Cell的高度,并将其返回给collectionView。你可以使用collectionView的bounds属性来获取collectionView的宽度,然后根据需要计算出不同的高度。\n\n记得将collectionView的delegate设置为当前的ViewController,并确保你的ViewController实现了UICollectionViewDataSource协议,以提供数据给collectionView。\n\n这样,每个Cell将根据你在sizeForItemAt方法中返回的高度进行布局。


原文地址: https://www.cveoy.top/t/topic/qyQj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录