[英]I have a UISwitch on the secondView, how do I control the switch method
[英]How do I navigate to my SecondView by tapping image button?
我正在尝试NavigationView
并希望在单击单选按钮时移至SecondView
。 如果我使用文本按钮,代码可以正常工作,但我需要使用图标/图像,但在这种情况下它不起作用。 我错过了什么?
import SwiftUI
struct FirstView: View {
var body: some View {
NavigationView {
VStack {
Text("Main Content View")
.font(.largeTitle)
.fontWeight(.medium)
strong text .foregroundColor(Color.blue)
Spacer()
NavigationLink(destination: SecondView(), label: {
Button(action: {
}) {
Image("radio-on-button")
.renderingMode(.original)
.resizable()
.frame(width: 75, height: 75)
.foregroundColor(.red)
.padding(.horizontal)
}
})
}
}
}
}
struct SecondView: View {
var body: some View {
Text("Hello, Second View!")
.font(.largeTitle)
.fontWeight(.medium)
.foregroundColor(Color.blue)
}
}
使用以下代码解决。 无需为NavigationLink
label 使用Button
,仅使用Image
作为NavigationLink
Label。
NavigationLink(destination: SecondView(), label: {
Image("radio-on-button") //Remove the button and add only Image
.renderingMode(.original)
.resizable()
.frame(width: 75, height: 75)
.foregroundColor(.red)
.padding(.horizontal)
})
当您想要导航时,您只需使用NavigationLink
而不使用Button
:
NavigationLink(destination: SecondView(), label: {
Image("radio-on-button")
.renderingMode(.original)
.resizable()
.frame(width: 75, height: 75)
.foregroundColor(.red)
.padding(.horizontal)
})
Button
用于执行某些操作。
这是完整的代码:
import SwiftUI
struct FirstView: View {
var body: some View {
NavigationView {
VStack {
Text("Main Content View")
.font(.largeTitle)
.fontWeight(.medium)
.foregroundColor(Color.blue)
NavigationLink {
SecondView()
} label: {
Image("radio-on-button")
.renderingMode(.original)
.resizable()
.frame(width: 75, height: 75)
.foregroundColor(.red)
.padding(.horizontal)
}
}
}
}
}
struct SecondView: View {
var body: some View {
Text("Hello, Second View!")
.font(.largeTitle)
.fontWeight(.medium)
.foregroundColor(Color.blue)
}
}
导航链接就像一个按钮,所以你可以像一个按钮一样设置它的样式。 我自己测试了代码,它可以工作。 将 label 部件视为另一个子视图。 这样,您可以在其中放置尽可能多的东西,并且每当用户点击该“子视图”内的任何内容时,都会出现第二个视图。
为了解决问题,您需要使用 NavigationLink 绑定和管理标签,因此在您的视图中创建一个 state 变量,如下所示,只需添加上面的正文。
@State var selection: Int? = nil
然后按如下方式更新您的按钮代码以添加 NavigationLink
NavigationLink(destination: SecondView(), label: {
Button(action: {
print("Radio button tapped")
self.selection = 1
}) {
Image("radio-on-button")
.renderingMode(.original)
.resizable()
.frame(width: 75, height: 75)
.foregroundColor(.red)
.padding(.horizontal)
}
})
我希望这能解决你的问题。 如果不放心可以讨论。 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.