
白色条应该与深色条的左侧对齐。我尝试过使用间隔符,或者更改各个对象的对齐方式,但都不起作用。这是我的代码:
VStack {
HStack {
Text("Calories eaten today:")
.foregroundColor(.white)
.fontWeight(.semibold)
Spacer(minLength: 100)
HStack {
ZStack(alignment: .leading) {
Capsule()
.rotation(.degrees(90))
.frame(width: 20, height: CGFloat((calorieGoal/proportion)))
.foregroundColor(.black)
.opacity(0.2)
Capsule()
.rotation(.degrees(90))
.frame(width: 20, height: CGFloat((Swift.min((eatendatabase.dayNutrients[0]/proportion), 180))), alignment: .leading)
}
Spacer(minLength: 20)
Text("\(String(format: "%.0f", eatendatabase.dayNutrients[0]))")
.font(.caption)
.foregroundColor(.white)
.frame(alignment: .trailing)
}
Spacer()
}
}
.padding(.horizontal, 30)发布于 2020-11-13 03:52:18
由于calorieGoal、proportional和eatendatabase.dayNutrients没有作为值提供,我使用了以下常量和变量来跟踪胶囊的宽度,我将在代码中将其表示为“进度条”:
let MAX_WIDTH: CGFloat = 100.0
let currentProgress: CGFloat = 40.0考虑到这一点,首先应该考虑将卡路里计数标签("832")移到包含进度条的HStack之外。其次,您在ZStack中嵌套了形成进度条的背景和前景胶囊。我们可以使用前景胶囊,并通过使用Spacer将其嵌套在HStack中将其与左侧对齐
HStack {
Capsule()
.rotation(.degrees(90))
.frame(width: 20.0, height: currentProgress /*This is the progress width of the bar, out of 100*/)
Spacer()
}当然,我们需要将HStack的宽度设置为背景胶囊的宽度,以便前景胶囊与背景胶囊的前缘正确对齐:
HStack {
...
}.frame(width: MAX_WIDTH)总体而言,以下是您的问题的可能解决方案:
VStack {
HStack {
Text("Calories eaten today:")
.foregroundColor(.white)
.fontWeight(.semibold)
// Made this font smaller for the preview
.font(.footnote)
// Add auto space between the label and the progress bar
Spacer()
// Separate the capsule progress bar from the calorie count
ZStack {
Capsule()
.rotation(.degrees(90))
.frame(width: 20.0, height: MAX_WIDTH /*This is the max width of the bar*/)
.foregroundColor(.black)
.opacity(0.2)
// Nesting the progress Capsule in an HStack so we can align it to the left
HStack {
Capsule()
.rotation(.degrees(90))
.frame(width: 20.0, height: currentProgress /*This is the progress width of the bar, out of 100*/)
// Adding a Spacer will force the Capsule to the left when it is in an HStack
Spacer()
}
// Set the frame width of the HStack to the same width as the background capsule
.frame(width: MAX_WIDTH)
}
// Add auto space between the progress bar and the calorie count
Spacer()
// The calorie count text, nested in an HStack with the label and the progress bar
Text("832")
.font(.caption)
.foregroundColor(.white)
.frame(alignment: .trailing)
}
}
.padding(.horizontal, 30)
// Added a gray background for the preview
.background(Color.gray)它看起来像这样:

https://stackoverflow.com/questions/64810366
复制相似问题