TL; DR:
我想在(父)状态更改时触发动作。在声明性上下文中,这似乎很困难。
备注
这里的挑战是我不试图使一个视图的属性依赖于另一个视图。那是个好地方。我可以(并且已经)整天阅读有关共享状态更改的信息。但这是一个事件。
我遇到的最好的是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 }
}
}
但是我希望这个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肯定不会强迫我 not 分解我的层次结构吗?
解决方案
这里是arsenius' suggestion。还有更快速的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)
}
}
}
答案 0 :(得分:1)
这是使用可选的外部事件生成器的一种可能方法,因此,如果提供的一个可重用视图对外部提供程序以及本地提供程序都做出了反应(如果不需要本地,则可以将其删除)。
通过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()
}
}
这个演示对我来说似乎最简单,也可以通过环境而不是构造函数间接依赖外部生成器注入。