uiimageview animation stops when user touches scre

2019-04-09 08:31发布

问题:

I have a UImageview with animated image. i am adding the uiimageview in code and its a part of a CollectionViewCell When the user touches the cell the animation stops, why does this happen?

code:

 var images: [UIImage] = []
for i in 0...10 {
   images.append(UIImage(named: "image\(i)"))
}

        let i = UIImageView(frame: CGRect(x: xPos, y: yPos, width: 200, height: 200))
        i.animationImages = images
        i.animationDuration = 0.5
        i.startAnimating()
        i.contentMode = UIViewContentMode.Center
        i.userInteractionEnabled = false

        self.addSubview(i) 

回答1:

In your custom collection view cell class, write following methods to fix issue

func setSelected(selected:Bool) {

}

func setHighlighted(higlighted:Bool) {

}


回答2:

Swift 4.0 Version:

override open var isSelected: Bool
{
    set {

    }

    get {
        return super.isSelected
    }
}

override open var isHighlighted: Bool
{
    set {

    }

    get {
        return super.isHighlighted
    }
}


回答3:

Overriding isSelected, isHighlighted with empty setter will solve this issue, but it will lose those two properties to be set. I was able to solve this issue by calling imageView.startAnimating() at didSelectItemAt in UICollectionViewDelegate.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let item = items[indexPath.item]
    if item.hasGIF {
        let cell = collectionView.cellForItem(at: indexPath) as! ItemCell
        cell.imageView.startAnimating()
    }
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let item = items[indexPath.item]
    if item.hasGIF {
        let cell = collectionView.cellForItem(at: indexPath) as! ItemCell
        cell.imageView.startAnimating()
    }
}


回答4:

In TableView Use code below can solve touche cancel, touche moved and so on

- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell startAnimation];
}