SwiftUI中如何移除无描述产品对应的Text视图空白区域
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.welcomeDescriptionsafely unwraps the optional description to avoidnilvalues.!desc.isEmptyensures 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

