Ternary operator inside NavigationLink SwiftUI

ぃ、小莉子 提交于 2021-02-05 08:24:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!