SwiftUI中旋转文本导致VStack随字符串长度变宽问题求助
问题解决思路及方案
问题核心:旋转后的Text会保留原水平布局的尺寸,导致VStack被文本长度撑开,设置padding无法解决该问题。
以下是几个直接可行的解决方法:
方法1:先限制Text宽度再旋转
给Text设置固定宽度,让它在旋转前就适配垂直显示的容器尺寸,避免撑开VStack:
var body: some View { VStack(spacing: 0) { Spacer() Text(title.uppercased()) .font(.footnote) .foregroundColor(.white) .frame(width: 20) // 提前限制Text宽度,匹配垂直显示需求 .rotationEffect(Angle(degrees: rotateClockwise ? 90 : -90)) Spacer() } .background(Color.gray.cornerRadius(12)) .frame(width: 85) }
方法2:固定水平尺寸,允许垂直自适应
使用fixedSize让Text仅在垂直方向自适应,水平方向不扩展:
var body: some View { VStack(spacing: 0) { Spacer() Text(title.uppercased()) .font(.footnote) .foregroundColor(.white) .fixedSize(horizontal: false, vertical: true) // 水平方向不撑开,垂直方向自适应 .rotationEffect(Angle(degrees: rotateClockwise ? 90 : -90)) Spacer() } .background(Color.gray.cornerRadius(12)) .frame(width: 85) }
方法3:裁剪超出容器的文本
如果不想限制Text宽度,可以通过裁剪去掉超出VStack范围的内容:
var body: some View { VStack(spacing: 0) { Spacer() Text(title.uppercased()) .font(.footnote) .foregroundColor(.white) .rotationEffect(Angle(degrees: rotateClockwise ? 90 : -90), anchor: .center) Spacer() } .background(Color.gray.cornerRadius(12)) .frame(width: 85) .clipped() // 裁剪超出frame的部分 }
注:你之前调整padding无效,是因为问题根源是旋转后文本的布局尺寸撑大了容器,而非内边距不足。
内容的提问来源于stack exchange,提问作者Scott
相关产品推荐
相关产品推荐

