我有一个包含Image和Text的VStack。我将Image的宽度(和高度)设置为屏幕宽度的一半:
struct PopularNow: View {
let item = popular[0]
var body: some View {
VStack(spacing: 5) {
Image(item.image)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: getRect().width/2, height: getRect().width/2)
Text(item.description)
.font(.caption)
.fontWeight(.bold)
.lineLimit(0)
}
.padding()
.background(Color.gray.opacity(0.1))
.cornerRadius(15)
}
func getRect() -> CGRect {
return UIScreen.main.bounds
}
}问题是Text会推动并导致VStack扩展,而不是尊重Image的宽度。我如何才能告诉Text不要水平增长超过Image的宽度,而是“垂直”增长(即添加所需的任意多行)?我知道我可以在VStack本身中添加frame修饰符,但这似乎是一个技巧。我想告诉Text只占用VStack已经拥有的空间宽度,而不是更多。
这就是它现在的样子,正如你可以看到的,VStack没有屏幕的一半大小,它是全屏幕大小,因为Text正在扩展它。

发布于 2021-04-20 01:35:36
试着固定它的大小,比如
VStack(spacing: 5) {
Image(item.image)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: getRect().width/2, height: getRect().width/2)
Text(item.description)
.font(.caption)
.fontWeight(.bold)
.lineLimit(0)
}
.fixedSize() // << here !!
// .fixedSize(horizontal: true, vertical: false) // alternate
.padding()https://stackoverflow.com/questions/67154177
复制相似问题