每次我使用 NavigationLink 時,目標引數都需要初始化結構的物件,從而產生不必要且混亂的代碼。
//View which will send me to another view using NavigationLink()
struct ProfileConfiguration: View {
NavigationLink(destination: ConfigurationCardView(person: Person.init(name: "",
bio: "",
location: ""))
)
}
//The destination view, which has the struct Person:
struct ConfigurationCardView: View {
var person: Person
var body: some View {
//Content
}
}
//The struct Person, with some variables:
struct Person: Hashable, Identifiable {
var name: String
var personImages: [UIImage?] = []
var bio: String
var location: String
}
uj5u.com熱心網友回復:
而不是在父視圖中硬編碼目標,您可以注入一個ViewBuilder將傳遞給的NavigationLink,例如:
struct ProfileConfiguration<CardView: View>: View {
let cardViewBuilder: () -> CardView
init(@ViewBuilder cardViewBuilder: @escaping () -> CardView) {
self.cardViewBuilder = cardViewBuilder
}
var body: some View {
NavigationLink(destination: cardViewBuilder, label: {})
}
}
uj5u.com熱心網友回復:
這不是必須的,有些視圖需要這些引數來顯示相關資料。
但是,如果您愿意,可以將該引數設為可選或提供默認值,這樣您就不必傳遞它了
uj5u.com熱心網友回復:
有兩種方法可以實作這一目標。
1 告訴 swift 物件可以保存由 ? 定義的 nil 值 (變種人:人?)
2 在 ConfigurationCardView 中為 person 物件分配一些值,所以 swift 不會要求傳遞 person 物件。
struct ConfigurationCardView: View {
var person: Person = Person.init(name: "",bio: "",location: "")
var body: some View {
//Content
}
}
在 1 種方法中,它仍然允許(非強制性)您從創建 NavigationLink 的外部傳遞人員物件。
在 2 方法中,如果您使用 var 定義人員,它仍然允許(非強制性)您從創建 NavigationLink 的外部傳遞人員物件。但是如果你用 let 定義,它將不允許你從外部傳遞 person 物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/483964.html
標籤:IOS 迅速 迅捷 swiftui-导航链接
