I was following the Apple tutorial for SwiftUI and in 'Interfacing with UIKit' they made us make a carousel of images (images of landmarks). When I tried to experiment with it I made it so that when you tap the Image it takes you to that Image's detail view. I also added a caption beneath the Images in the carousel and I wanted that caption to take you to a small write-up about that particular Landmark when tapped. However, only the caption took you to its destination whereas the Image didn't do anything (Although it does highlight when you press down on it).
I won't dump the exact code but I've made a simplified version which has the same setup and gets my point across. I'll add comments to make it less tedious to understand.
struct ContentView: View {
@State var currentPage = 0 // Tracks page number of the Carousel.
var body: some View {
NavigationView {
List {
Carousel(currentPage: $currentPage)
.listRowInsets(EdgeInsets())
Text("Page number: \(currentPage + 1)") // Displays page number of Carousel.
}
}
}
}
struct Carousel: View {
@Binding var currentPage: Int
var body: some View {
VStack {
PageView([Photo(), Photo()], currentPage: $currentPage) // This is a view from the Apple Tutorial. I'll link it incase you want to check out the code for this.
.equatable() // This allows the Text which shows the page number to work. I've made the '==' operator to always return true for the sake of simplicity.
.frame(height: 350)
NavigationLink(destination: Text("Write-up about landmark")) {
Text("\"Captions...\"") // This changes in the real app depending on the page number. This NavigationLink always works and takes me to the correct page.
.font(.headline)
.padding(.bottom, 10)
}
.padding(.trailing)
}
}
}
struct Photo: View {
var body: some View {
NavigationLink(destination: Text("Landmark Detail")) { // This NavigationLink doesn't work. It highlights when pressed down on, but doesn't take you anywhere.
Image(systemName: "person") // These are the respective landmarks in the real app.
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: UIScreen.screenWidth) // Custom static property. It's equal to UIScreen.main.bounds.size.width
}
}
}
Link to the PageView struct: https://developer.apple.com/tutorials/swiftui/interfacing-with-uikit#create-view-to-represent-a-uipageviewcontroller (section 3 step 3)
(Note: Since I'm tracking the currentPage
variable in ContentView
instead of PageView
, the currentPage
variable inside of PageView
is a Binding
instead of a State
in my code)
If someone can explain how I can make the NavigationLink work please let me know. If you're too lazy to write the code you can just give an explanation of how to do it and I'll figure it out from there.
Thanks in advance!