更新:将代码更新为Swift 5.6
使用UIBezierPath
和CAKeyFrameAnimation
。
以下是代码:
let circlePath = UIBezierPath(arcCenter: view.center, radius: 20, startAngle: 0, endAngle: .pi*2, clockwise: true)
let animation = CAKeyframeAnimation(keyPath: #keyPath(CALayer.position))
animation.path = circlePath.cgPath
animation.duration = 1
animation.repeatCount = .infinity
let squareView = UIView()
// whatever the value of origin for squareView will not affect the animation
squareView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
squareView.backgroundColor = .lightGray
view.addSubview(squareView)
// you can also pass any unique string value for key
squareView.layer.add(animation, forKey: nil)
// circleLayer is only used to show the circle animation path
let circleLayer = CAShapeLayer()
circleLayer.path = circlePath.cgPath
circleLayer.strokeColor = UIColor.black.cgColor
circleLayer.fillColor = UIColor.clear.cgColor
view.layer.addSublayer(circleLayer)
这是截图:
此外,您可以设置 squareView.layer
的 anchorPoint
属性,使视图不以其中心点为锚点进行动画。 anchorPoint
的默认值为 (0.5, 0.5),表示中心点。
let animation = CAKeyframeAnimation(keyPath: "position")
中,(keyPath: "position") 实际上引用了一个必需的属性... 我以为你可以将键路径字符串命名为任何你想要的东西哈哈:P现在可以用了! - Justinadd(_:forKey:)
方法移动到您的按钮单击回调中。 - Cokile Ceoi