如何覆盖 SwiftUI 中 NavigationView 和 NavigationStack 的默认行为?

huangapple go评论50阅读模式
英文:

How to override default behaviour of NavigationView and NavigationStack in SwiftUI?

问题

我好奇,是否有一种方法可以在SwiftUI中导航时覆盖默认的滑动效果?这里有一些代码,我试图使用.transition来影响动画,但没有成功:

struct TransitionOnNavigation: View {
    var body: some View {
        NavigationStack {
            NavigationLink("Press Me") {
                Text("Hello World!")
                    .transition(.move(edge: .bottom)) // 这没有起作用
            }
        }
    }
}

我感到惊讶的是,我在搜索中没有找到关于这个基本问题的任何信息,而且我不记得在WWDC视频中看到过相关内容。我确实找到了这个库,但我想知道是否有内置的功能我可能遗漏了。

理想情况下,我想要:

  1. 更改过渡的基本类型(移动、缩放、淡入淡出等)

  2. 影响动画的速度(例如使用duration参数)

  3. 有能力使用matchedGeometryEffect以有趣的方式控制各个视图。

英文:

I'm curious, is there a way to override the default slide-in behaviour when navigating in SwiftUI? Here's some code where I'm unsuccessfully attempting to use .transition to affect the animation:

struct TransitionOnNavigation: View {
    var body: some View {
        NavigationStack {
            NavigationLink("Press Me") {
                Text("Hello World!")
                    .transition(.move(edge: .bottom)) // this doesn't do anything
            }
        }
    }
}

I'm surprised that I haven't found anything in my searches for something so fundamental, and I don't recall seeing anything about this in WWDC videos. I did find this library, but I wonder if there's something built-in that I'm missing.

Ideally, I'd want to:

  1. Change the basic type of transition (move, scale, fade, etc)

  2. Affect the rate of animation (eg using duration parameters)

  3. Have the ability to use matchedGeometryEffect control individual views in interesting ways.

答案1

得分: 1

根据我所知,SwiftUI 在使用 NavigationStack / NavigationSplitView 时本身支持自定义视图之间的过渡效果。
你可以尝试使用 NavigationTransition,它支持 iOS 16 上的 NavigationStack。

将这个包添加到你的项目并导入:

import NavigationTransitions

然后:

NavigationStack {
    // 你的内容
}
.navigationTransition(.fade(.cross))

你还可以组合预定义的过渡效果或创建自定义的过渡效果。

英文:

As per I know SwiftUI natively supports custom transition between Views when using NavigationStack / NavigationSplitView.
You can try with NavigationTransition which supports NavigationStack on iOS 16.

Add package to you project and import

import NavigationTransitions

Then

NavigationStack {
    // your content
}
.navigationTransition(.fade(.cross))

You can also combine predefined transitions or make a custom one.

huangapple
  • 本文由 发表于 2023年7月11日 11:32:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76658552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定