Повернуть поворот на 360 градусов на неопределенный срок в Swift?

Я хочу вращать изображение на 360 градусов бесконечно.

UIView.animate(withDuration: 2, delay: 0, options: [.repeat], animations: {
    self.view.transform = CGAffineTransform(rotationAngle: 6.28318530717959)
}, completion: nil)

Как мне это сделать?

Ответы

Ответ 1

Swift 2.x способ неограниченного вращения UIView, скомпилированный из более ранних ответов:

// Rotate <targetView> indefinitely
private func rotateView(targetView: UIView, duration: Double = 1.0) {
    UIView.animateWithDuration(duration, delay: 0.0, options: .CurveLinear, animations: {
        targetView.transform = CGAffineTransformRotate(targetView.transform, CGFloat(M_PI))
    }) { finished in
        self.rotateView(targetView, duration: duration)
    }
}

ОБНОВЛЕНИЕ Swift 3.x

// Rotate <targetView> indefinitely
private func rotateView(targetView: UIView, duration: Double = 1.0) {
    UIView.animate(withDuration: duration, delay: 0.0, options: .curveLinear, animations: {
        targetView.transform = targetView.transform.rotated(by: CGFloat(M_PI))
    }) { finished in
        self.rotateView(targetView: targetView, duration: duration)
    }
}

Ответ 2

Swift 3.0

    let imgViewRing = UIImageView(image: UIImage(named: "apple"))
    imgViewRing.frame = CGRect(x: 0, y: 0, width: UIImage(named: "apple")!.size.width, height: UIImage(named: "apple")!.size.height)
    imgViewRing.center = CGPoint(x: self.view.frame.size.width/2.0, y: self.view.frame.size.height/2.0)
    rotateAnimation(imageView: imgViewRing)
    self.view.addSubview(imgViewRing)

Это логика анимации

func rotateAnimation(imageView:UIImageView,duration: CFTimeInterval = 2.0) {
        let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
        rotateAnimation.fromValue = 0.0
        rotateAnimation.toValue = CGFloat(.pi * 2.0)
        rotateAnimation.duration = duration
        rotateAnimation.repeatCount = Float.greatestFiniteMagnitude;

        imageView.layer.add(rotateAnimation, forKey: nil)
    }

Вы можете проверить вывод по этой ссылке

Ответ 3

Используйте это расширение для поворота UIImageView на 360 градусов.

extension UIView {
func rotate360Degrees(duration: CFTimeInterval = 1.0, completionDelegate: AnyObject? = nil) {
    let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
    rotateAnimation.fromValue = 0.0
    rotateAnimation.toValue = CGFloat(M_PI)
    rotateAnimation.duration = duration

    if let delegate: CAAnimationDelegate = completionDelegate as! CAAnimationDelegate? {
        rotateAnimation.delegate = delegate
    }
    self.layer.addAnimation(rotateAnimation, forKey: nil)
}
}

Чем вращать UIImageView, просто используйте этот метод

self.YOUR_SUBVIEW.rotate360Degrees()

Ответ 4

Я бы использовал его как функцию rotateImage(), а в коде завершения просто вызывал rotateImage() снова. Я думаю, вы должны использовать M_PI (или быстрый эквивалент) для количества оборотов, однако.

Ответ 5

Это работает для меня в Swift 2.2:

let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = 360 * CGFloat(M_PI/180)
let innerAnimationDuration : CGFloat = 1.0
rotationAnimation.duration = Double(innerAnimationDuration)
rotationAnimation.repeatCount = HUGE
self.imageView.addAnimation(rotationAnimation, forKey: "rotateInner")

Ответ 6

Обновлен для Swift 3: Я сделал расширение для UIView и включил следующую функцию внутри:

func rotate(fromValue: CGFloat, toValue: CGFloat, duration: CFTimeInterval = 1.0, completionDelegate: Any? = nil) {

let rotateAnimation = CABasicAnimation(keyPath: >"transform.rotation")
rotateAnimation.fromValue = fromValue
rotateAnimation.toValue = toValue
rotateAnimation.duration = duration

if let delegate: Any = completionDelegate {
rotateAnimation.delegate = delegate as? CAAnimationDelegate
}
self.layer.add(rotateAnimation, forKey: nil)

}

Затем вы можете вызвать функцию через (например, в UIView, который я сделал с кнопкой):

monitorButton.rotate(fromValue: 0.0, toValue: CGFloat(M_PI * 2), completionDelegate: self)

Надеюсь, это поможет!

Ответ 7

Попробуйте это, он работает для меня, я вращаю изображение на один раз

 UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveLinear, animations: {

       self.imgViewReload.transform = CGAffineTransformRotate(self.imgViewReload.transform, CGFloat(M_PI))

 }, completion: {
    (value: Bool) in

          UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveLinear, animations: {
          self.imgViewReload.transform = CGAffineTransformIdentity

         }, completion: nil)
 })

Ответ 8

На вкладке tabBarController убедитесь, что вы установите делегат и выполните следующий метод doSelect:

func tabBarController(_ tabBarController: UITabBarController,
                          didSelect viewController: UIViewController) {
        if let selectedItem:UITabBarItem = tabBarController.tabBar.selectedItem {
            animated(tabBar: tabBarController.tabBar, selectedItem: selectedItem)
        }
    }




fileprivate func animated(tabBar: UITabBar, selectedItem:UITabBarItem){
        if let view:UIView = selectedItem.value(forKey: "view") as? UIView {
            if let currentImageView = view.subviews.first as? UIImageView {
                rotate(imageView: currentImageView, completion: { (completed) in
                    self.restore(imageView: currentImageView, completion: nil)
                })
            }
        }
    }

    fileprivate func rotate(imageView:UIImageView, completion:((Bool) ->Void)?){
        UIView.animate(withDuration: animationSpeed, delay: 0.0, options: .curveLinear, animations: {
            imageView.transform = CGAffineTransform.init(rotationAngle: CGFloat.pi)
        }, completion: {
            (value: Bool) in
            completion?(value)
        })
    }

    fileprivate func restore(imageView:UIImageView, completion:((Bool) ->Void)?){
        UIView.animate(withDuration: animationSpeed, delay: 0.0, options: .curveLinear, animations: {
            imageView.transform = CGAffineTransform.identity
        }, completion: {
            (value: Bool) in
            completion?(value)
        })
    }

Ответ 9

Принятый ответ не был идеальным для моей ситуации.
Я хотел повернуть изображение на 360 градусов, 4 раза с продолжительностью вращения 1 секунда.
Во время ротации анимация не была одинаковой на разных телефонах iPhone 6 против iPhone X.
Более того, когда на экране было 10 видов, и им приходилось выполнять одну и ту же анимацию, некоторые зацикливались один раз, другие зацикливались очень быстро, другие зацикливались очень медленно.

Единственное решение, которое было кратким и непротиворечивым на всех iPhone и на всех экранах, независимо от количества, было это: fooobar.com/info/30858/...