And*_*can 2 animation event-handling view-hierarchy swiftui
长话短说:
我想在(父)状态发生变化时触发一个操作。这在声明性上下文中似乎很困难。
评论
这里的挑战是我并不试图使一种视图的属性依赖于另一种视图。这是一个覆盖良好的领域。我可以(并且已经)整天阅读有关共享状态更改的内容。但这是一个事件。
我遇到的最好的是arsenius的。他的方法确实有效。我想知道是否有一种更具反应性的方法来做到这一点。也许是一击Publisher?看起来很粗略。
代码
在 FRP 中,“事件”并不总是一个肮脏的词。我可以通过处理相同的View事件来启动动画: View
import SwiftUI
struct MyReusableSubview : View {
@State private var offs = CGFloat.zero // Animate this.
var body: some View {
Rectangle().foregroundColor(.green).offset(y: self.offs)
// A local event triggers the action...
.onTapGesture { self.simplifiedAnimation() }
// ...but we want to animate when parent view says so.
}
private func simplifiedAnimation() {
self.offs = 200
withAnimation { self.offs = 0 }
}
}
Run Code Online (Sandbox Code Playgroud)
但我希望它是View可组合和可重用的。将其插入到更大的层次结构中似乎是合理的,该层次结构对于何时运行动画有自己的想法。我所有的“解决方案”要么在View更新期间改变状态,要么甚至无法编译。
struct ContentView: View {
var body: some View {
VStack {
Button(action: {
// Want this to trigger subview's animation.
}) {
Text("Tap me")
}
MyReusableSubview()
}.background(Color.gray)
}
}
Run Code Online (Sandbox Code Playgroud)
SwiftUI 肯定不会强迫我不要分解我的层次结构吗?
解决方案
这是阿森纽斯的建议。有没有更 Swifty-UI 的方式?
struct MyReusableSubview : View {
@Binding var doIt : Bool // Bound to parent
// ... as before...
var body: some View {
Group {
if self.doIt {
ZStack { EmptyView() }
.onAppear { self.simplifiedAnimation() }
// And call DispatchQueue to clear the doIt flag.
}
Rectangle()
.foregroundColor(.green)
.offset(y: self.offs)
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是一种使用可选外部事件生成器的可能方法,因此,如果提供的可重用视图对外部提供者以及本地提供者做出反应(如果不需要本地,则可以将其删除)。
使用 Xcode 11.4 / iOS 13.4 进行测试

完整模块代码:
import SwiftUI
import Combine
struct MyReusableSubview : View {
private let publisher: AnyPublisher<Bool, Never>
init(_ publisher: AnyPublisher<Bool, Never> =
Just(false).dropFirst().eraseToAnyPublisher()) {
self.publisher = publisher
}
@State private var offs = CGFloat.zero // Animate this.
var body: some View {
Rectangle().foregroundColor(.green).offset(y: self.offs)
// A local event triggers the action...
.onTapGesture { self.simplifiedAnimation() }
.onReceive(publisher) { _ in self.simplifiedAnimation() }
// ...but we want to animate when parent view says so.
}
private func simplifiedAnimation() {
self.offs = 200
withAnimation { self.offs = 0 }
}
}
struct TestParentToChildEvent: View {
let generator = PassthroughSubject<Bool, Never>()
var body: some View {
VStack {
Button("Tap") { self.generator.send(true) }
Divider()
MyReusableSubview(generator.eraseToAnyPublisher())
.frame(width: 300, height: 200)
}
}
}
struct TestParentToChildEvent_Previews: PreviewProvider {
static var previews: some View {
TestParentToChildEvent()
}
}
Run Code Online (Sandbox Code Playgroud)
这个演示对我来说似乎最简单,也可以通过环境而不是构造函数间接依赖注入外部生成器。