You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中如何移除无描述产品对应的Text视图空白区域

Fixing Blank Space for Empty Descriptions in SwiftUI Menu List

Hey there! I see the issue you're facing—when a menu item has no description, that empty Text view is still taking up space in your VStack, creating that unwanted gap. Let's fix this with a simple conditional check.

The Problem

Your current code always renders the description Text view, even when welcomeDescription is nil or an empty string:

Text(men.welcomeDescription ?? "")
    .font(.caption)
    .foregroundColor(.gray)

Even an empty Text occupies vertical space (thanks to the VStack's spacing: 10), which is why you're seeing that blank spot.

The Solution

Only render the description Text if there's actual content to show. Use optional binding combined with a check for non-empty string:

Replace your existing description Text line with this:

if let desc = men.welcomeDescription, !desc.isEmpty {
    Text(desc)
        .font(.caption)
        .foregroundColor(.gray)
}

How It Works

  • if let desc = men.welcomeDescription safely unwraps the optional description to avoid nil values.
  • !desc.isEmpty ensures we don't render anything if the string is just empty whitespace or blank.

With this change, the description view will only appear when there's content, and your VStack will collapse the spacing automatically—removing that annoying blank area exactly like your desired second image.

Updated Code Snippet (Relevant Part)

Here's how your VStack will look after the fix:

VStack(alignment: .leading, spacing: 10) {
    Spacer()
    Text(men.name)
        .font(.system(size: 16))
        .foregroundColor(.black)
        .fontWeight(.semibold)
    // Conditional description render
    if let desc = men.welcomeDescription, !desc.isEmpty {
        Text(desc)
            .font(.caption)
            .foregroundColor(.gray)
    }
    HStack {
        Text("\(men.price) lei")
            .fontWeight(.bold)
        Text("\(men.ingredients.map({$0.grams}).reduce(0, +), specifier: \"%.0f\")g")
            .font(.system(size: 16))
            .fontWeight(.medium)
            .foregroundColor(.gray)
    }
    Spacer()
}

That should do the trick! Your menu list will now cleanly skip the description section when there's no content, matching your expected layout.

内容的提问来源于stack exchange,提问作者4265756b69

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 12:22:33