SwiftUI中能否根据Button标签宽度自动调整RoundedRectangle宽度?
解决方案
当然可行,不需要用GeometryReader,调整代码结构就能实现——把RoundedRectangle作为Button的背景,而非用ZStack单独渲染,这样矩形会自动适配Button内容的宽度。
修改后的代码如下:
Button { viewModel.startNewGame() } label: { HStack { Text("New Game") Image(systemName: "return") } .font(.title2) .foregroundStyle(.white) .padding(.horizontal, 20) // 控制内容与矩形边缘的间距 .frame(height: 50) // 保留固定高度,宽度自动适配内容 } .background( RoundedRectangle(cornerRadius: 12) )
关键修改说明
- 移除原ZStack,将
RoundedRectangle设为Button的background,SwiftUI会自动让背景匹配Button的内在尺寸(内容+padding的大小) - 给label内的HStack添加水平padding,避免文字/图标紧贴矩形边框,提升视觉效果
- 保留了原需求的固定高度,若希望高度也自适应内容,可移除
.frame(height: 50)
内容的提问来源于stack exchange,提问作者Vakhtang Saginadze
相关产品推荐
相关产品推荐

