I’m tinkering with SwiftUI-NavigationSplitView. I started with this example from the official Developer-documentation.
The UI, I have made is very similar:
import SwiftUI
struct ContentView: View {
@State var articles = [Article]()
@State var selectedArticle: Article?
var body: some View {
NavigationSplitView {
List(selection: $selectedArticle) {
ForEach(articles) { article in
// With attached .tag-modifier it works fine.
Text(article.name) // .tag(article)
}
}
} detail: {
VStack(alignment: .leading) {
Text(selectedArticle?.name ?? "")
.font(.title2)
.bold()
Text(selectedArticle?.desc ?? "")
Spacer()
}.padding()
}
.onChange(of: selectedArticle, {
print(selectedArticle?.id)
print(" ------------- ")
})
.onAppear() {
for i in 1...6 {
let article = Article(
name: "Name_\(i)",
desc: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.\nIn enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus."
)
articles.append(article)
}
}
}
}
#Preview {
ContentView()
}
Previously it hadn’t the .tag-modifier attached to the list-items.
It didn’t work. The selectedArticle-variable never changed.
Finally I found a forum-post, where I saw the usage of .tag. That remind me, how it could work.
But I still don’t understand the example of Apple.
How is it possible, that the Apple-example works? In case it really works.
Can someone give some insights?
Has it to do with the usage of IDs?