如何将图片按钮、操作和导航链接组合在一起?
我在尝试理解如何让按钮在执行一个动作的同时导航到一个新的界面,如下所示(下面的代码在一个简单的结构体中):
Button(action: {
print("I am new to SwiftUI!")
buttonFunction()
}) {
NavigationLink {
NewUI()
} label: {
Image(buttonImage)
.resizable()
.frame(maxWidth:50, maxHeight:50)
}
有了上面的代码,我能够让导航到NewUI的动作执行,但按钮的操作不会执行。print语句从未输出。
接着我尝试把顺序反过来,如下所示:
NavigationLink {
NewUI()
} label: {
Button(action: {
print("Oh no, this only prints!")
buttonFunction()
}) {
Image(buttonImage)
.resizable()
.frame(maxWidth:50, maxHeight:50)
}
但这次只会输出这条语句(buttonFunction执行),导航不会执行。
我在想也许解决方案涉及把导航链接的调用迁移到函数中,如下所示:
func buttonFunction() {
// do some cool function stuff here
// once done, somehow call for the navigation to execute
}
然而,在我看来似乎没法把那段代码放进一个函数中。当我尝试时出现了错误。
有什么解决办法吗?
我也读过这里的一些类似问题,有人提到TapGesture()。我也尝试过,但还是没成功。
解决方案
我通过使用 navigationDestination(isPresented:destination:) 找到了这个解决方案:
struct YourView: View {
@State private var navigate = false
var body: some View {
Button(action: {
someButtonFunction()
navigate = true
}) {
Image("buttonImage")
}
.navigationDestination(isPresented: $navigate) {
DestinationView()
}
}
func someButtonFunction() {
// all your logic here
}
}
按照 Seikh Imran的回答 的指示,我把 @State private var navigate 放进了 Struct。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。