【发布时间】:2020-03-26 21:05:06
【问题描述】:
我有一个 SwiftUI watchOS 应用程序,它使用 NavigationLinks 在几个视图之间进行路由。我正在使用NavigationLink 的tag 和selection 参数来控制哪个视图可见。在我的真实应用程序中,当用户从复杂功能启动应用程序时,我希望能够导航回索引 0 处的视图。但是,每当 $selection 值不是 nil 或 0 并且 $selection 在我的视图模型中设置为 0 时,索引 0 处的视图会短暂显示,然后 $selection 被 SwiftUI 重置为 nil(两次) 没有任何用户交互导致它。
我创建了一个示例应用程序来演示此行为,并带有一个近似于用户从复杂功能启动的计时器。我将选择值以外的所有内容都设为常量,以尝试消除差异作为可能的来源。
这是一个演示发生了什么的 gif:
import SwiftUI
struct Item: Identifiable {
let id: Int
let text: String
}
class ContentViewModel: ObservableObject {
@Published public var selectedIndex: Int? {
didSet {
print("ContentViewModel selectedIndex = \(String(describing: selectedIndex))")
}
}
public let items: [Item] = [
Item(id: 0, text: "Zero"),
Item(id: 1, text: "One"),
Item(id: 2, text: "Two"),
Item(id: 3, text: "Three"),
Item(id: 4, text: "Four")
]
private var timer: Timer?
init() {
self.timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { [unowned self] _ in
print("ContentViewModel timer fired")
self.selectedIndex = 0
}
}
}
struct ContentView: View {
@ObservedObject private var viewModel = ContentViewModel()
var body: some View {
List(self.viewModel.items) { (item: Item) in
NavigationLink(destination: Text(item.text), tag: item.id, selection: self.$viewModel.selectedIndex) {
Text(item.text)
}
}
}
}
这是控制台中记录的内容:
ContentViewModel selectedIndex = Optional(2)
ContentViewModel timer fired
ContentViewModel selectedIndex = Optional(0)
ContentViewModel selectedIndex = nil
ContentViewModel selectedIndex = nil
ContentViewModel selectedIndex = Optional(3)
ContentViewModel timer fired
ContentViewModel selectedIndex = Optional(0)
ContentViewModel selectedIndex = nil
ContentViewModel selectedIndex = nil
我希望你们能提供任何帮助或指点!
注意:我正在运行所有东西的最新版本,Xcode 11.4、Swift 5.2、watchOS 6.2。
【问题讨论】:
-
我也在 iPhone 上的 Xcode12.0.1 上看到了这个。在我的情况下,它是由更新 EnvironmentObject 上的 Published var 引起的。谢天谢地,我真的不需要发布那个 var,所以我删除了属性包装器。但是,在 iOS13 和 Xcode 12.0.1 上运行时不会发生这种行为