gpt4 book ai didi

swift - RxSwift 使用 RxCocoa 与动画绑定(bind)

转载 作者:行者123 更新时间:2023-11-28 07:46:16 24 4
gpt4 key购买 nike

我有一个绑定(bind)到 UILabel 文本的 UIStepper 值:

    unitsStepper.rx.value.asObservable()
.map { Int($0).description }
.bind(to: stepperCountLabel.rx.text)
.disposed(by: rx.disposeBag)

而且我想在标签每次更改时都设置动画,有比这个更好的方法吗?

    unitsStepper.rx.value.asObservable()
.map { Int($0).description }.subscribe(onNext: { [weak self] value in
guard let strongSelf = self else { return }
UIView.animate(withDuration: 0.4, animations: {
strongSelf.stepperCountLabel.text = value
strongSelf.stepperCountLabel.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
}, completion: { completed in
strongSelf.stepperCountLabel.transform = CGAffineTransform.identity
})

}).disposed(by: rx.disposeBag)

最佳答案

就我个人而言,我不认为这有什么不妥。如果您希望它更具可读性、更少嵌套,那么您可以将其拆分开来。您的需求会有所不同,并且您不想用非常具体的东西污染一般的东西,但看起来您有一些重复的东西,一种脉动。

我需要类似的东西来进行表单验证,并写下了这个(虽然你的实际动画更简单,我想我从多部分关键帧动画开始但将其减少到只是来回)

extension UIView {

func shake(totalDuration: TimeInterval, totalCycles: Int = 1) {

let animationDuration = totalDuration / Double(totalCycles)
let wiggle = CAKeyframeAnimation(keyPath: "transform.rotation.z")
wiggle.values = [0.0, -0.04, 0.04, 0.0]
wiggle.duration = animationDuration
wiggle.repeatCount = Float(totalCycles)
layer.add(wiggle, forKey: "wiggle")

let vertical = CAKeyframeAnimation(keyPath: "transform.translation.y")
vertical.values = [0.0, -2.0, 2.0, 0]
vertical.duration = animationDuration
vertical.repeatCount = Float(totalCycles)
layer.add(vertical, forKey: "vertical")

let horizontal = CAKeyframeAnimation(keyPath: "transform.translation.x")
horizontal.values = [0.0, 2.0, -2.0, 0]
horizontal.duration = animationDuration
horizontal.repeatCount = Float(totalCycles)
layer.add(horizontal, forKey: "horizontal")
}

func pulse(totalDuration: TimeInterval, ratio: CGFloat = 1.2) {

UIView.animateKeyframes(
withDuration: totalDuration,
delay: 0,
options: [],
animations: {
UIView.addKeyframe(
withRelativeStartTime: 0,
relativeDuration: 0.5,
animations: { [unowned self] in
self.transform = .init(scaleX: ratio, y: ratio)

})
UIView.addKeyframe(
withRelativeStartTime: 0.5,
relativeDuration: 0.5,
animations: { [unowned self] in
self.transform = .identity
})
}, completion: { completed in })
}
}

然后我编写了一个带有条件和 Action 闭包的简单验证器结构,并在表单更改/验证时快速浏览它们的列表。

但是回到你的问题,你的动画本身是最小的,如果它是一次性的,你可以把它放在封闭类中,如果它是通用的,你可以将它作为扩展添加,但是作为一个-关闭,它仍然很好(如果我正在阅读代码)

关于swift - RxSwift 使用 RxCocoa 与动画绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50952562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com