如果您不需要以模式或动画的形式呈现您的视图,您应该使用编程导航(NavigationLink with selection binding)来获得所需的行为。
例如,如果它是您的应用程序的根目录,则以下内容应该有效:
struct Item: Identifiable {
let id: Int
let name: String
}
struct NormalNav: View {
@State var items: [Item] = [
.init(id: 0, name: "One"),
.init(id: 1, name: "Two"),
.init(id: 2, name: "Three")
]
@State private var selection: Int? = 1
var body: some View {
NavigationView {
List {
ForEach(items) { item in
NavigationLink(item.name,
destination: Text(item.name),
tag: item.id,
selection: $selection)
}
}
}
}
}
上面的视图应该直接打开到第二个项目(“Two”),没有动画。
但是,有一个皱纹。如果您需要在 Sheet 中显示此视图,则会使用动画推送详细视图,这可能不是您想要的。
在this answer 的基础上,您可以在初始创建时抑制动画,但在后续导航时将其重新打开:
struct ContentView: View {
@State var items: [Item] = [
.init(id: 0, name: "One"),
.init(id: 1, name: "Two"),
.init(id: 2, name: "Three")
]
@State private var selection: Int? = nil
@State var isAnimationDisabled = true
@State var isListPresented = false
var body: some View {
Button("Show list") {
isListPresented = true
}.sheet(isPresented: $isListPresented) {
NavigationView {
List {
ForEach(items) { item in
NavigationLink(item.name,
destination: Text(item.name),
tag: item.id,
selection: $selection)
}
}.animations(disabled: isAnimationDisabled)
}.onChange(of: selection) { value in
if value == nil {
isAnimationDisabled = false
}
}.onAppear {
selection = 1
}
}
}
}
extension View {
func animations(disabled: Bool) -> some View {
transaction { (tx: inout Transaction) in
guard disabled else {
return
}
tx.disablesAnimations = true
tx.animation = .none
}
}
}