swiftUI多行文本在Vstack对齐中未按预期处理



当文本输入是多行时,我面临对齐问题。在本例中,第一部分显示了图像中正确显示的左侧和右侧文本。第二部分,它显示了3到4行干扰对齐的文本右

我想让左边在多行中独立大小。右边保持原样(第二个标题和第二个值之间没有间隔)。

代码:

struct ContentView: View {
var body: some View {

Form {
Section {
Text("single line")
}

TwoLineView(firstTitle: "1st Title", fistValue: "Value",
secondTitle: "2nd Title", secondValue: "2nd Value")

TwoLineView(firstTitle: "1st Title", fistValue: "test",
secondTitle: "2nd Title", secondValue: "2nd Value")

Section {
Text("mutiple lines")
}

TwoLineView(firstTitle: "1st Title", fistValue: "This is long. This is long value. This is long value",
secondTitle: "2nd Title", secondValue: "2nd Value")

TwoLineView(firstTitle: "1st Title", fistValue: "test",
secondTitle: "2nd Title", secondValue: "2nd Value")
}

}




struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
}

struct TwoLineView: View{
var firstTitle: String
var fistValue: String
var secondTitle: String
var secondValue: String

var body: some View {
HStack(alignment: VerticalAlignment.center, spacing: 0) {
VStack(alignment: HorizontalAlignment.leading, spacing: 0) {
Text(firstTitle).lineLimit(1)
.font(.system(size: 30, weight: .heavy, design: .default))

Text(fistValue)
.frame(maxHeight: .infinity)
}
Spacer()
VStack(alignment: HorizontalAlignment.leading, spacing: 0) {
Text(secondTitle).lineLimit(1)
.font(.system(size: 30, weight: .heavy, design: .default))

Text(secondValue).lineLimit(1)

Spacer()

}
Spacer(minLength: 45)
}
}
}

期望值:单行或多行值。我不想在标题和值之间显示空白。(图片的第二部分在第二个标题和第二个值之间有一个间隙,这是一个糟糕的用户体验)

尝试下面的代码,删除。frame(maxHeight: .infinity)并添加spacer():

struct ContentView: View {
var body: some View {

Form {
Section {
Text("single line")
}

TwoLineView(firstTitle: "1st Title", fistValue: "Value",
secondTitle: "2nd Title", secondValue: "2nd Value")

TwoLineView(firstTitle: "1st Title", fistValue: "test",
secondTitle: "2nd Title", secondValue: "2nd Value")

Section {
Text("mutiple lines")
}

TwoLineView(firstTitle: "1st Title", fistValue: "This is long. This is long value. This is long value",
secondTitle: "2nd Title", secondValue: "2nd Value")

TwoLineView(firstTitle: "1st Title", fistValue: "test",
secondTitle: "2nd Title", secondValue: "2nd Value")
}

}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
}

struct TwoLineView: View{
var firstTitle: String
var fistValue: String
var secondTitle: String
var secondValue: String

var body: some View {
HStack(alignment: VerticalAlignment.center, spacing: 0) {
VStack(alignment: HorizontalAlignment.leading, spacing: 0) {
Text(firstTitle).lineLimit(1)
.font(.system(size: 30, weight: .heavy, design: .default))

Text(fistValue) //<------here
Spacer()     //<-------here
}
Spacer()
VStack(alignment: HorizontalAlignment.leading, spacing: 0) {
Text(secondTitle).lineLimit(1)
.font(.system(size: 30, weight: .heavy, design: .default))

Text(secondValue).lineLimit(1)

Spacer()

}
Spacer(minLength: 45)
}
}
}

最新更新