![](/img/trans.png)
[英]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.