簡體   English   中英

如何通過單擊按鈕在 Swift UI 中從一個視圖導航到另一個視圖

[英]How to navigate from one view to another in Swift UI on a click of button

我想通過單擊按鈕在 SwiftUI 中從一個視圖推送到另一個視圖。 同樣,我們在 storyboard 中從一個 controller 導航到另一個 controller。

但是在 SwiftUI 如何實現這一點。

您可以使用 NavigationLink 解決它

什么是導航鏈接?

NavigationLink:在每個單元格的右側創建一個按鈕並觸發顯示到詳細視圖

蘋果鏈接: https://developer.apple.com/documentation/swiftui/navigationlink

示例項目

蘋果https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation

Github https://github.com/appbrewery/H4X0R-News-iOS13-SwiftUI-Completed

如何實施:

import SwiftUI

struct LandmarkList: View {
    var body: some View {
        NavigationView {
            List(landmarkData) { landmark in
                NavigationLink(destination: LandmarkDetail(landmark: landmark)) {
                    LandmarkRow(landmark: landmark)
                }
            }
            .navigationBarTitle(Text("Landmarks"))
        }
    }
}

*注意:“LandmarkDetail”是您的目標視圖。

你也可以從蘋果下載示例項目(上面提到的鏈接)以清楚地理解它

有兩種方法可以實現這一目標。

第一個是“isActive”綁定。

struct ViewA: View {

    @State private var isActive = false

    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: NextView(),
                               isActive: $isActive) {
                        Button(action: {
                            self.isActive = true
                        }) {
                            Text("Push Next View")
                        }
                }
            }
        }
    }

}

您將要推送的視圖放置在 NavigationLink 的目的地中。 第二種方法是再次使用 NavigationLink,但使用“標簽”和“選擇”。 There the navigation is activated when the selection matches the tag.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM