gpt4 book ai didi

animation - SwiftUI ViewModifier 动画每次都无法正确显示

转载 作者:行者123 更新时间:2023-12-05 05:37:41 25 4
gpt4 key购买 nike

我创建了一个 ViewModifier,它在其内容的右侧添加了一个图标,我希望图标显示的方式是将 .clipShape() 修饰符从 -50 设置为 0,问题是第一次出现时,它只是弹出而没有动画,最后一次消失时也会发生同样的事情。在底部你会发现一个视频演示

到目前为止我的 ViewModifier

extension View {
func addRightIcon(icon: Image, show: Bool) -> some View {
return modifier(RightIconModifier(icon: icon, show: show))
}
}

struct RightIconModifier: ViewModifier {

var icon: Image
private var iconMask: Int = 0

init(icon: Image, show: Bool) {
self.icon = icon
withAnimation(Animation.interpolatingSpring(stiffness: 170, damping: 15).delay(2.5)) {
iconMask = show ? 0 : -50
}
}

func body(content: Content) -> some View {
ZStack {
content
.overlay(rightIcon)
}
}

var rightIcon: some View {
icon
.font(.system(size: 25))
.foregroundColor(.black)
.frame(maxWidth: .infinity,
maxHeight: .infinity,
alignment: .trailing)
.padding()
.clipShape(Rectangle().offset(x: CGFloat(iconMask)))
}
}

这将是我如何使用它的一个简短版本,希望你能得到一个让它工作的想法

TextField(placeholder, text: $text).addRightIcon(icon: Image(systemName: "checkmark"), show: isTextValid)

var isTextValid: Bool {
if !text.isEmpty {
let validation = NSPredicate(format: "SELF MATCHES %@", "[’a-zA-Z]{3,20}")
let validated = validation.evaluate(with: text)
return validated
}
return false
}

This is a video demonstration

最佳答案

Animatable 修饰符应该在 body 中(直接或从 body 中调用),而不是在 init 中。修饰符也是一个结构,因此如果它的属性在外部被修改,它们也是可动画的。

所以这里是固定的ViewModifier。使用 Xcode 14/iOS 16 测试

注意:出于测试目的,我简化了动画和滤镜

enter image description here

struct RightIconModifier: ViewModifier {

var icon: Image
var show: Bool // << injected changes

func body(content: Content) -> some View {
ZStack {
content
.overlay(rightIcon)
}
}

var rightIcon: some View {
icon
.font(.system(size: 25))
.foregroundColor(.black)
.frame(maxWidth: .infinity,
maxHeight: .infinity,
alignment: .trailing)
.padding()
.clipShape(Rectangle().offset(x: CGFloat(show ? 0 : -50))) // << switch is here !!
.animation(.easeIn(duration: 1), // << simplified for testing
value: show)
}
}

Test module on GitHub

关于animation - SwiftUI ViewModifier 动画每次都无法正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73084339/

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