[英]SwiftUI View with StateObject, a Form element and a ForEach breaks bindings when trying to use NavigationLink Inside the form
OK something weird is going on and I want to see if anyone else have this issue.好的,发生了一些奇怪的事情,我想看看其他人是否有这个问题。
Consider the following ViewModel
class with one published property to use from a View:考虑以下
ViewModel
class 以及一个可从视图使用的已发布属性:
final class ViewModel: ObservableObject {
@Published var isActive = false
}
When using this view:使用此视图时:
struct MainView: View {
@StateObject var viewModel = ViewModel()
var body: some View {
NavigationView {
Form {
NavigationLink (
destination: ChildView(isActive: $viewModel.isActive),
isActive: $viewModel.isActive,
label: { Text("Go to child view") }
)
// Adding this ForEach causes the NavigationLink above to have a broken binding
ForEach(1..<4) {
Text("\($0)")
}
}
.navigationBarTitle("Test")
}
}
}
And this SubView:而这个子视图:
struct ChildView: View {
@Binding var isActive: Bool
var body: some View {
Button("Go back", action: { isActive = false })
}
}
The expected result is when tapping on "Go to child view", navigating to the subview and tapping "Go back" to return to the main view - it should navigate back using the isActive
binding.预期的结果是当点击“转到子视图”时,导航到子视图并点击“返回”返回主视图 - 它应该使用
isActive
绑定导航回来。
But actually, the button "Go Back" Doesn't work.但实际上,“返回”按钮不起作用。
BUT If I remove the ForEach
element from the form in the main view, the button works again.但是,如果我从主视图的表单中删除
ForEach
元素,则该按钮将再次起作用。 And it looks like the ForEach
breaks everything.看起来
ForEach
打破了一切。
Form
to VStack
fixes the issueForm
更改为VStack
可解决此问题@State
also fixes the issue@State
也可以解决问题ForEach
to a subview fixes the issue but as soon as I pass the viewmodel or part of it to the subview as a binding or as a ObservedObject - it still brokenForEach
提取到子视图可以解决问题,但是一旦我将视图模型或其一部分作为绑定或 ObservedObject 传递给子视图 - 它仍然损坏Can anything advise if there is a logical issue with the code or is it a SwiftUI bug?如果代码存在逻辑问题或者是 SwiftUI 错误,有什么建议吗? Any suggestions for a workaround?
任何解决方法的建议?
https://i.stack.imgur.com/BaggK.gif https://i.stack.imgur.com/BaggK.gif
Apple developer forum discussion: https://developer.apple.com/forums/thread/674127苹果开发者论坛讨论: https://developer.apple.com/forums/thread/674127
It looks like the issue has been fixed in the latest iOS 14.5 Beta 2看起来该问题已在最新的 iOS 14.5 Beta 2 中得到修复
The issue has been fixed on iOS 14.5该问题已在 iOS 14.5 上修复
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.