gpt4 book ai didi

animation - SwiftUI - 响应父 View 中的点击

转载 作者:行者123 更新时间:2023-12-02 02:57:22 25 4
gpt4 key购买 nike

TL;博士:

我想在(父)状态发生变化时触发操作。这在声明性上下文中似乎很困难。

备注

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

我遇到的最好的来自 arsenius 。他的方法确实有效。我想知道是否有一种更具 react 性的方法来做到这一点。也许是一次性的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 }
}
}

但我想要这个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' suggestion 。有没有更 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)
}
}
}

最佳答案

这是一种使用可选外部事件生成器的可能方法,因此,如果一个提供的可重用 View 对外部提供者以及本地提供者使用react(如果不需要本地,则可以将其删除)。

使用 Xcode 11.4/iOS 13.4 进行测试

demo

完整模块代码:

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

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

关于animation - SwiftUI - 响应父 View 中的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60822763/

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