白色条应该与深色条的左侧对齐。我试过使用间隔器,或改变单个对象的对齐方式,但没有任何效果。这是我的代码:
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)
最佳答案
如 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)
它看起来像这样:关于swift - 在 ZStack 中对齐对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64810366/