首页 > 解决方案 > SwiftUI - 响应父视图中的点击

问题描述

TL;博士:

我想在(父)状态改变时触发一个动作。这在声明性上下文中似乎很困难。

评论

这里的挑战是我不想让一个视图的属性依赖于另一个视图。那是覆盖良好的领域。我可以(并且已经)整天阅读有关共享状态更改的信息。但这是一个事件

我遇到的最好的是arsenius。他的方法确实有效。我想知道是否有更被动的方式来做到这一点。也许是一击Publisher?看起来很粗略。

代码

“事件”在 FRP 中并不总是一个肮脏的词。我可以通过处理同一View事件来启动 a 的动画: 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 }
    }
}

但我希望这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)
    }
}

SwiftUI 肯定不会强迫我不要分解我的层次结构吗?

解决方案

这是arsenius 的建议。有没有更 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)
        }
    }
}

标签: animationevent-handlingswiftuiview-hierarchy

解决方案


这是使用可选外部事件生成器的可能方法,因此,如果提供的可重用视图对外部提供者以及本地做出反应(如果不需要本地,则可以将其删除)。

使用 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()
    }
}

这个演示对我来说似乎最简单,也可以通过环境而不是构造函数间接依赖注入外部生成器。


推荐阅读