问题
I have a problem when trying to user ternary operator on a button in NavigationLink. I have an array of campaigns, which is displayed in a carouselView. Bellow carousel there is a button(NavigationLink) for opening another view which displays details of the campaign. The array of campaigns is empty initially, so I have to check if self.cardCampaigns > 0, if that is true it should navigate to a view which displays details of the campaign, otherwise ignore( I am trying to show a view with text "No campaigns available". I am using ternary operator for that, but it's not working. I get "Result values in '? :' expression have mismatching types 'CampaignDetailsView' and 'Text'" error where I use ternary operator.
My code is bellow:
NavigationLink(destination:
self.cardCampaigns.count > 0 ? CampaignDetailsView(viewModel: CampaignDetailsViewModel(campaign: cardCampaigns[self.count].campaign)) : Text("No Campaign found")
) {
ZStack {
RoundedRectangle(cornerRadius: 8)
.foregroundColor(Color.orOrangeColor)
.frame(width: 300, height: 50)
Text("Details")
.foregroundColor(.white)
}
}
回答1:
This is because the types of CampaignDetailsView and Text don't match. You need to use a @ViewBuilder (or just a Group, VStack etc).
Here is a solution with the destination view as a @ViewBuilder computed property:
@ViewBuilder
var destinationView: some View {
if cardCampaigns.count > 0 {
CampaignDetailsView(viewModel: CampaignDetailsViewModel(campaign: cardCampaigns[self.count].campaign))
} else {
Text("No Campaign found")
}
}
Which you can use like this:
NavigationLink(destination: destinationView) { ... }
来源:https://stackoverflow.com/questions/64089212/ternary-operator-inside-navigationlink-swiftui