ios - 旋转按钮动画不起作用

标签 ios swift uiview

我有一个按钮,当点击它时,它应该自行旋转,这是我的代码:

@IBAction func calculateButtonTapped(_ sender: UIButton) {
    let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
    rotateAnimation.fromValue = 0.0
    rotateAnimation.toValue = CGFloat(M_PI)
    rotateAnimation.speed = 3.0
    rotateAnimation.repeatCount = 6000
    calculateButton.layer.add(rotateAnimation, forKey: nil)

    DispatchQueue.main.async {
        self.openCircle(withCenter: sender.center, dataSource: self.calculator!.iterateWPItems())
        self.calculateButton.layer.removeAllAnimations()
    }
}

但是,有时当我点击按钮时,它会立即返回正常状态然后旋转,有时按钮会变为暗选择状态,并且根本不动画,动画之后的任务将完成。如果我不停止动画,它会在 openCircle 完成后开始。

可能是什么原因?

最佳答案

  1. 您没有设置动画的持续时间。 替换这个

rotateAnimation.speed = 3.0

有了这个

rotateAnimation.duration = 3.0
  • @alexburtnik and it's ok to block the main thread

  • 不,这不行。您应该在 openCircle 方法中添加一个 completion 参数,并在动画(或其他内容)完成时调用它。如果阻塞主线程,用户界面将会卡住,强烈建议不要这样做。

  • 如果您不确定在主线程上调用了 calculateButtonTapped,您也应该分派(dispatch)方法的第一部分。与 UI 相关的所有内容必须在主线程上完成。
  • 它看起来应该类似于:

    @IBAction func calculateButtonTapped(_ sender: UIButton) {
        let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
        rotateAnimation.fromValue = 0.0
        rotateAnimation.toValue = CGFloat(M_PI)
        rotateAnimation.duration = 3.0
        rotateAnimation.repeatCount = .infinity //endless animation
        calculateButton.layer.add(rotateAnimation, forKey: nil)
    
        self.openCircle(
            withCenter: sender.center,
            dataSource: self.calculator!.iterateWPItems(),
            completion: {
                self.calculateButton.layer.removeAllAnimations()
        })
    }
    
    func openCircle(withCenter: CGPoint, dataSource: DataSourceProtocol, completion: (()->Void)?) {
        //do your staff and call completion when you're finished
        //don't block main thread!
    }
    

    关于ios - 旋转按钮动画不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40376737/

    相关文章:

    ios - 如何使用自定义转换 ios7 制作 uiview 全屏 View Controller

    objective-c - 找不到类方法

    ios - 我的 Xcode 8 有什么问题?我什至无法编译新项目?

    ios - 如何手动加载 UITableView

    json - Alamofire 响应序列化失败

    swift - Definespresentationcontext 导致搜索器下的内容转移?

    ios - 实现自定义表格 View 单元格

    ios - 苹果手机 : is there any secure way to establish 2-way SSL from an application

    ios - iOS7 上的 UICollectionViewCell 中的 UIImageView 自动布局问题,但在 iOS8 上没问题

    objective-c - 如何使用自动布局以编程方式创建 UITableView?