如何在UICollectionView单元格中显示活动指示器?

问题描述 投票:-1回答:1

我想在每个单元格中显示活动指示器,直到UICollectionView单元格的图像显示出来,但它只在最后一个单元格中显示。

view

我的代码

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath)

    cell.backgroundColor = .blue
    let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 160, height: 200))
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 160, height: 200))

    cell.contentView.addSubview(activityIndicator)
    activityIndicator.startAnimating()

    containerView.backgroundColor = .magenta

    containerView.addSubview(imageView)

    guard imageArray.count == tempListLength && tempListLength > 0 else {
        DispatchQueue.main.async {
            self.activityIndicator.center = cell.contentView.center
        }
        return cell
    }

    DispatchQueue.main.async {
        self.activityIndicator.stopAnimating()
    }
    imageView.image = imageArray[indexPath.row]

    cell.contentView.addSubview(imageView)

    return cell
}
swift uicollectionview uicollectionviewcell activity-indicator
1个回答
1
投票

在你的自定义单元格中添加活动指示器

class CustomCell: UICollectionViewCell {

  private lazy var spinner = UIActivityIndicatorView(style: .large)

        override init(frame: CGRect) {
            super.init(frame: frame)
            commonInit()
        }

        required init?(coder: NSCoder) {
            super.init(coder: coder)
            commonInit()
        }

        private func commonInit() {
             spinner.translatesAutoresizingMaskIntoConstraints = false
            contentView.addSubview(spinner)

            spinner.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
            spinner.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
         }
    }

然后在cellForItemAt方法中,你只需要做的是启动动画和停止动画。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath)

   cell.spinner.startAnimating() 
// OR
  cell.spinner.stopAnimating()

}
© www.soinside.com 2019 - 2024. All rights reserved.