обновление: Обновление кода Swift 4. Там нет никакой разницы между Swift 3 и 4 Swift для фрагмента кода ниже.
Использовать UIBezierPath
и CAKeyFrameAnimation
.
Вот код:
//The code is within viewDidLoad method
let circlePath = UIBezierPath(arcCenter: view.center, radius: 20, startAngle: 0, endAngle: .pi*2, clockwise: true)
let animation = CAKeyframeAnimation(keyPath: "position")
animation.duration = 1
animation.repeatCount = MAXFLOAT
animation.path = circlePath.cgPath
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 locate 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)
Вот захват:
Кроме того, вы можете установить anchorPoint
свойство squareView.layer
, чтобы сделать вид не живой якорь в его центре , Значение по умолчанию anchorPoint
равно (0,5, 0,5), что означает центральную точку.
Очень круто. Большое спасибо! – user4806509