我有一个具有4个主要视图的项目。这是包含NavigationView的ContentView的主体。我添加了修饰符 .navigationViewStyle(StackNavigationViewStyle()),所以我没有在横向模式下获得拆分视图导航。
ContentView.swift:
var body: some View {
NavigationView {
VStack(alignment: .center, spacing: 10) {
Text("Scoreboard")
.font(.custom("Chalkduster", size: 50))
Button(action: {
self.new_game = true
}) {
Text("New Game")
.font(.custom("Chalkduster", size: 20))
.foregroundColor(.black)
}
NavigationLink(destination: CreateGameView(TEST_NAV: self.$new_game), isActive: $new_game) {
EmptyView()
}
//.isDetailLink(false)
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
这导致我的应用在某些情况下崩溃,我不确定为什么。如果我删除此行,但将 .isDetailLink(false)添加到每个NavigationLink(在ContentView.swift,CreateGameView.swift和GameView.swift上都有一个),也会导致此问题。我不确定如何用一些代码片段简要地说明问题,所以我认为最好的方法是为整个项目提供重新创建崩溃的步骤。这是该项目的github:https://github.com/steve3424/scoreboard_project
要重新创建崩溃,请执行以下操作:
从我读到的内容来看:
How to debug "precondition failure" in Xcode?
https://www.reddit.com/r/iOSProgramming/comments/eis04m/precondition_failure_invalid_input_index/
我认为这与GeometryReader有关。我在这里唯一使用GeometryReader的地方:
GameView.swift第29行:
struct TrackableScrollView<Content>: View where Content: View {
let axes: Axis.Set
let showIndicators: Bool
@Binding var contentOffset: CGFloat
let content: Content
init(_ axes: Axis.Set = .vertical, showIndicators: Bool = true, contentOffset: Binding<CGFloat>, @ViewBuilder content: () -> Content) {
self.axes = axes
self.showIndicators = showIndicators
self._contentOffset = contentOffset
self.content = content()
}
var body: some View {
GeometryReader { outsideProxy in
ScrollView(self.axes, showsIndicators: self.showIndicators) {
ZStack(alignment: self.axes == .vertical ? .top : .leading) {
GeometryReader { insideProxy in
Color.clear
.preference(key: ScrollOffsetPreferenceKey.self, value: [self.calculateContentOffset(fromOutsideProxy: outsideProxy, insideProxy: insideProxy)])
// Send value to the parent
}
VStack {
self.content
}
}
}
.onPreferenceChange(ScrollOffsetPreferenceKey.self) { value in
self.contentOffset = value[0]
}
// Get the value then assign to offset binding
}
}
private func calculateContentOffset(fromOutsideProxy outsideProxy: GeometryProxy, insideProxy: GeometryProxy) -> CGFloat {
if axes == .vertical {
return (insideProxy.frame(in: .global).minY - outsideProxy.frame(in: .global).minY)
} else {
return (insideProxy.frame(in: .global).minX - outsideProxy.frame(in: .global).minX)
}
}
}
上面是在此处创建的可跟踪滚动视图:https://medium.com/@maxnatchanon/swiftui-how-to-get-content-offset-from-scrollview-5ce1f84603ec
它允许我从垂直和水平滚动视图中获取滚动偏移量,并与主网格的移动相匹配。
现在,注释掉ContentView.swift中显示的 .navigationViewStyle(StackNavigationViewStyle())(如上所示)。重复这些步骤,应该不会发生崩溃。这是我发现的唯一可以解决崩溃的问题。
有人知道为什么会这样吗?有没有一种方法可以解决此崩溃而不删除 .navigationViewStyle(StackNavigationViewStyle())?