NavigationLink SwiftUI 中的三元运算符

问题描述:

我在 NavigationLink 中的按钮上尝试使用三元运算符时遇到问题.我有一系列广告系列,显示在 carouselView 中.Bellow carousel 有一个按钮(NavigationLink)用于打开另一个显示活动详细信息的视图.活动数组最初是空的,所以我必须检查 self.cardCampaigns >0,如果这是真的,它应该导航到显示活动详细信息的视图,否则忽略(我试图显示带有文本无活动可用"的视图.我为此使用了三元运算符,但它不起作用. 我在使用三元运算符的地方得到'Result values in '? :' expression has mismatching types 'CampaignDetailsView' and 'Text'" 错误.

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.

我的代码如下:

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)
    }
}

这是因为 CampaignDetailsViewText 的类型不匹配.您需要使用 @ViewBuilder(或只是一个 GroupVStack 等).

This is because the types of CampaignDetailsView and Text don't match. You need to use a @ViewBuilder (or just a Group, VStack etc).

这是一个将目标视图作为 @ViewBuilder 计算属性的解决方案:

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")
    }
}

你可以这样使用:

NavigationLink(destination: destinationView) { ... }