ios - 中断 UIView 转换

标签 ios swift uiview uiviewanimation uiviewanimationtransition

是否有可能在 iOS 上中断 UIView.transition 的当前状态?

给你一些背景信息:我有一个 UIButton ,我需要在其中设置标题颜色的动画 - 不过,动画可以附加不同的延迟。由于 UIView.transition 不支持延迟,所以我只是延迟了整个 block 的执行:

DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
    UIView.transition(with: button, duration: 0.4, options: [.beginFromCurrentState, .allowUserInteraction, .transitionCrossDissolve], animations: {
        button.setTitleColor(selected ? .red : .black, for: .normal)
    }, completion: nil)
}

这里的问题是,如果这段代码以不同的延迟快速连续执行,结果可能会出乎意料。例如,可以使用 selected=true,delay=0.5 调用,然后立即使用 selected=false,delay=0.0 调用。在这种情况下,按钮最终会变成红色,即使它应该是黑色的。

因此,我正在寻找一种方法来延迟 UIView.transform、中断 UIView.transform 或使 setTitleColor() code> 可通过 UIView.animate 进行动画处理。

最佳答案

我实际上创建了一个框架来专门执行此操作,您可以触发相对于时间进度或值插值进度的动画。框架和文档可以在这里找到:

https://github.com/AntonTheDev/FlightAnimator

以下示例假设您有一个 CATextLayer 支持的 View ,因为这不是如何设置它的问题,这里有一个小示例可以帮助您入门:

class CircleProgressView: UIView {
    .....

    override class func layerClass() -> AnyClass {
        return CircleProgressLayer.self
    }
}

示例1:

假设您有一个 CATextLayer 支持的 View ,我们可以按如下方式为其前景色设置动画,并触发另一个相对于时间的动画:

var midPointColor = UIColor.orange.cgColor
var finalColor    = UIColor.orange.cgColor
var keyPath       = "foregroundColor"

textView.animate { [unowned self] (a) in
    a.value(midPointColor, forKeyPath : keyPath).duration(1.0).easing(.OutCubic)

    // This will trigger the interruption 
    // at 0.5 seconds into the animation

    animator.triggerOnProgress(0.5, onView: self.textView, animator: { (a) in
        a.value(finalColor, forKeyPath : keyPath).duration(1.0).easing(.OutCubic)
    })
}

示例2:

就像前面的示例一样,一旦您有了 CATextLayer 支持的 View ,我们就可以相对于 RBG 值的进度矩阵对其前景颜色进行动画处理,根据 3 个值的进度大小进行计算:

var midPointColor = UIColor.orange.cgColor
var finalColor    = UIColor.orange.cgColor
var keyPath       = "foregroundColor"

textView.animate { [unowned self] (a) in
    a.value(midPointColor, forKeyPath : keyPath).duration(1.0).easing(.OutCubic)

    // This will trigger the interruption 
    // when the magnitude of the starting point
    // is equal to 0.5 relative to the final point

    a.triggerOnValueProgress(0.5, onView: self.textView, animator: { (a) in
        a.value(finalColor, forKeyPath : keyPath).duration(1.0).easing(.OutCubic)
    })
}

希望这有帮助:)

关于ios - 中断 UIView 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53007191/

相关文章:

ios - 模拟器的 XCode 位置选择器被禁用?

ios - 当 Swift 中的表中的特定内容发生更改时更改表的标题

Swift:让自定义进度 View 跟随用户点击?用户界面贝塞尔曲线

ios - Apple HealthKit 葡萄糖水平读数出现转换错误

ios - 无法删除随机添加的 UIView

iphone - didReceiveMemoryWarning 和 viewDidUnload

ios - 检查此运行中是否已打开 View

android - 在 Chromecast 上播放 Widevine DRM

ios - 分离的 ViewController 错误

swift - 在分支中引用 switch 语句的值