如何让WrappingHStack内按钮的文本自动换行而非截断?
方法1:给Button内部的VStack设置最大宽度
在Button的VStack的frame配置中添加maxWidth: .infinity,让VStack填充WrappingHStack分配的可用宽度,从而让Text在该宽度范围内自动换行。
修改后的代码:
WrappingHStack(0..<sentences.count, id:\.self, alignment: .center) { i in Button(action: { // }) { VStack { Text("A very long sentence. Hopefully it will flow onto the next line") .font(.system(size: 18, weight: .bold, design: .rounded)) .foregroundColor(.white) } // 添加maxWidth约束,让VStack自适应可用宽度 .frame(maxWidth: .infinity, alignment: .leading) .padding() .background( RoundedRectangle(cornerRadius: 6) .fill(colours[i]) ) .padding(5) } .padding(.bottom, 10) }
方法2:给Text设置强制换行属性
如果方法1未生效,可以给Text添加fixedSize(horizontal: false, vertical: true),明确允许垂直方向自动换行,同时不固定水平宽度:
Text("A very long sentence. Hopefully it will flow onto the next line") .font(.system(size: 18, weight: .bold, design: .rounded)) .foregroundColor(.white) .fixedSize(horizontal: false, vertical: true)
原因说明
WrappingHStack默认会根据子元素的理想宽度布局,当Button内部视图没有明确宽度约束时,Text会优先保持单行显示,直到被容器强制截断。通过设置maxWidth: .infinity或fixedSize,可以让视图优先利用可用空间进行换行,而非维持单行的理想宽度。
内容的提问来源于stack exchange,提问作者Joseph
相关产品推荐
相关产品推荐

