我使用UICollectionView制作了画廊。

如果降低屏幕,图像应继续显示并停在20。

该代码不断更新。
但是,设置单元格大小的函数collectionView(_:layout:sizeForItemAt :)不起作用。
因此,仅连续显示20张图像。

在viewDidLoad()

if let layoutt = artCollectionView?.collectionViewLayout as? PinterestLayout
{
    layoutt.delegate = self
}

单元格设置
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCollectionViewCell", for: indexPath) as? HomeCollectionViewCell,

    let arts = self.artList else { return HomeCollectionViewCell() }
    if arts.count > indexPath.row
    {
        let model = arts[indexPath.row]

        cell.imgView.sd_setImage(with: URLHelper.createEncodedURL(url: model.thumburl), completed: nil)
    }
    return cell
}

返回单元格大小
extension HomeViewController : PinterestLayoutDelegate
{
    func collectionView(_ collectionView: UICollectionView, heightForPhotoAtIndexPath indexPath:IndexPath) -> CGFloat
    {
        return CGFloat(300.0)
    }
}

目前,该功能仅在应用启动时执行一次。您知道我想每次运行该功能的方法吗?

最佳答案

请按照以下步骤在PinterestLayout中安装UICollectionView

PinterestLayout设置为您的集合视图。

let layout = PinterestLayout()
collectionView.collectionViewLayout = layout

设置布局
layout.delegate = self
layout.cellPadding = 5
layout.numberOfColumns = 2
PinterestLayoutDelegate的实现方法
extension CustomCollectionVC: PinterestLayoutDelegate {

    func collectionView(collectionView: UICollectionView,
                        heightForImageAtIndexPath indexPath: IndexPath,
                        withWidth: CGFloat) -> CGFloat {
        let image = images[indexPath.item]

        return image.height(forWidth: withWidth)
    }

    func collectionView(collectionView: UICollectionView,
                        heightForAnnotationAtIndexPath indexPath: IndexPath,
                        withWidth: CGFloat) -> CGFloat {
        let textFont = UIFont(name: "Arial-ItalicMT", size: 11)!
        return "Some text".heightForWidth(width: withWidth, font: textFont)
    }
}

加载数据时,会使布局无效,并在集合视图上重新加载数据。
collectionView.collectionViewLayout.invalidateLayout()
collectionView.reloadData()

观察值:
func collectionView(_ collectionView: UICollectionView, heightForPhotoAtIndexPath indexPath:IndexPath) -> CGFloat

试试这个而不是上面的:
func collectionView(collectionView: UICollectionView,
                        heightForImageAtIndexPath indexPath: IndexPath,
                        withWidth: CGFloat) -> CGFloat

关于ios - 在Swift 4中调用collectionView(_:layout:sizeForItemAt :),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53003494/

10-10 21:33