我目前正在尝试为用户的经验条添加动画。
如果我将动画放在collectionViewController中,动画会被成功加载(一次)。但是,如果我将动画放在headerView中(因为我想在个人资料图片上添加条形图),则该条形图会被多次启动。
如果我将动画放在collectionViewController中,动画会被成功加载(一次)。但是,如果我将动画放在headerView中(因为我想在个人资料图片上添加条形图),则该条形图会被多次启动。
这是我的代码(headerViewCell):
let shapeLayerXp = CAShapeLayer()
override func layoutSubviews() {
super.layoutSubviews()
showUserXp()
self.animateXp(toValue: 1)
}
func showUserXp() {
let center = profileImage.center
let circularPath = UIBezierPath(arcCenter: center, radius: 40, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)
shapeLayerXp.path = circularPath.cgPath
let color = UIColor(red: 122 / 255, green: 205 / 255, blue: 186 / 255, alpha: 1)
shapeLayerXp.strokeColor = color.cgColor
shapeLayerXp.lineWidth = 4
shapeLayerXp.fillColor = UIColor.clear.cgColor
shapeLayerXp.lineCap = kCALineCapRound
shapeLayerXp.strokeEnd = 0
self.contentView.layer.addSublayer(shapeLayerXp)
}
func animateXp(toValue: Int) {
let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
basicAnimation.toValue = toValue
basicAnimation.duration = 2
basicAnimation.fillMode = kCAFillModeForwards
basicAnimation.isRemovedOnCompletion = false
shapeLayerXp.add(basicAnimation, forKey: "urSoBasic")
}
是这样启动的:
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerViewCell = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header", for: indexPath) as! UserHeaderView
// ....
return cell
}
layoutSubViews()
中调用showUserXp()
和animateXp()
,因此每次系统决定布局标题单元格时都会再次发生动画。显然,当集合视图滚动时会发生这种情况,但也可能在其他时间发生,例如设备旋转、标题单元格重用等。你想要实现什么目的?它只应该在控制器首次显示时进行动画,然后只在某些其他时间进行动画吗? - Upholder Of Truth