问题描述
我正在尝试在Text
内制作两个vstack
,以占据父对象(vstack
)的整个宽度。
我完全没有主意。
这就是我所拥有的:
var body: some View {
vstack(alignment: .center,spacing: 0) {
Image("image")
.resizable()
.scaledToFill()
.frame(height: 190)
.clipped()
vstack(alignment: .leading,spacing: 8) {
Text(title)
.font(.title)
.background(Color.red)
.fixedSize(horizontal: false,vertical: true)
Text(subtitle)
.font(.subheadline)
.background(Color.yellow)
.fixedSize(horizontal: false,vertical: true)
}
.frame(minWidth: 0,maxWidth: .infinity)
.background(Color.green)
.padding(.top,24)
.padding(.horizontal,24)
Button(buttonTitle) { print("Something") }
.frame(maxWidth: .infinity,minHeight: 56)
.background(Color.red)
.foregroundColor(.white)
.cornerRadius(56/2)
.padding(.top,32)
.padding(.horizontal,24)
.padding(.bottom,20.0)
}.background(Color.blue)
.cornerRadius(38)
.frame(minWidth: 0,maxWidth: UIScreen.main.bounds.size.width - 48)
}
这是它的外观:
我该如何实现?!
解决方法
- 同时删除两个文本上的.fixedSize
- 改为添加.frame(minWidth:0,maxWidth:.infinity)
- 在SwiftUI中,事情的顺序也很重要,因此您需要在.frame之后添加.background。
最终结果将是:
Text("title")
.font(.title)
.frame(minWidth: 0,maxWidth: .infinity)
.background(Color.red)
要使其左对齐:
HStack {
Text("title")
.font(.title)
Spacer(minLength: 0)
}
.background(Color.red)
,
这是可能的解决方法
VStack(alignment: .leading,spacing: 8) {
Text(title)
.font(.title)
.frame(maxWidth: .infinity) // << here
.background(Color.red)
.fixedSize(horizontal: false,vertical: true)
Text(subtitle)
.font(.subheadline)
.frame(maxWidth: .infinity) // << here
.background(Color.yellow)
.fixedSize(horizontal: false,vertical: true)
}
.frame(maxWidth: .infinity) // << here