我想在屏幕上有一个类似“徽章”的东西,当满足条件时,它会从正常尺寸弹到更大,然后反复恢复到正常尺寸,直到不再满足条件。不过,我似乎无法让徽章停止“弹跳”。一旦开始,就势不可挡。
我尝试过的:我尝试过使用一些动画,但它们可以分为使用“repeatForever”来实现所需效果的动画和不使用“repeatForever”的动画。例如:
Animation.default.repeatForever(autoreverses: true)
and
Animation.spring(response: 1, dampingFraction: 0, blendDuration: 1)
(将阻尼设置为 0 使其永远消失)
然后用 .animation(nil) 替换它。似乎不起作用。有人有什么想法吗?提前非常感谢!这是重现它的代码:
struct theProblem: View {
@State var active: Bool = false
var body: some View {
Circle()
.scaleEffect( active ? 1.08: 1)
.animation( active ? Animation.default.repeatForever(autoreverses: true): nil )
.frame(width: 100, height: 100)
.onTapGesture {
self.active = !self.active
}
}
}
我想到了!
一个动画使用 .repeatForever()
如果将动画替换为 nil
. 如果你用相同的动画替换它但没有 .repeatForever()
。 (或者使用任何其他停止的动画,因此您可以使用持续时间为 0 的线性动画来立即停止)
换句话说,这是行不通的:.animation(active ? Animation.default.repeatForever() : nil)
但这确实有效:.animation(active ? Animation.default.repeatForever() : Animation.default)
为了使其更具可读性和易于使用,我将其放入一个扩展中,您可以像这样使用: .animation(Animation.default.repeat(while: active))
这是一个使用我的扩展的交互式示例,您可以使用实时预览来测试它:
import SwiftUI
extension Animation {
func `repeat`(while expression: Bool, autoreverses: Bool = true) -> Animation {
if expression {
return self.repeatForever(autoreverses: autoreverses)
} else {
return self
}
}
}
struct TheSolution: View {
@State var active: Bool = false
var body: some View {
Circle()
.scaleEffect( active ? 1.08: 1)
.animation(Animation.default.repeat(while: active))
.frame(width: 100, height: 100)
.onTapGesture {
self.active.toggle()
}
}
}
struct TheSolution_Previews: PreviewProvider {
static var previews: some View {
TheSolution()
}
}
据我所知,一旦您分配了动画,它就不会消失,直到您的视图完全停止。因此,如果您将 .default 动画设置为永久重复并自动反转,然后指定持续时间为 4 的线性动画,您会注意到默认的重复动画仍在继续,但它的移动速度越来越慢,直到它停止。在 4 秒结束时完全停止。因此,我们通过线性动画将默认动画设置为停止。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)