我想在每个单元格中显示活动指示器,直到UICollectionView单元格的图像显示出来,但它只在最后一个单元格中显示。
我的代码
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
}
在你的自定义单元格中添加活动指示器
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()
}