我正在开发我的第一个SwiftUI应用程序,它想要显示一个类别的List,并用一个徽章来指示该类别中的项目数量。类别的标题将在左侧,徽章将在行上右对齐。该列表将由NavigationLink组成,因此点击其中一个将进一步深入到视图层次结构中。我编写的呈现NavigationLink的代码如下所示:
List {
ForEach(myItems.indices) { categoryIndex in
let category = categories[categoryIndex]
let title = category.title
let fetchReq = FetchRequest<MyEntity>(entity: MyEntity(),
animation: .default)
NavigationLink(destination: MyItemView()) {
HStack(alignment: .center) {
Text(title)
Spacer()
ZStack {
Circle()
.foregroundColor(.gray)
Text("\(myItemsDict[category]?.count ?? 0)")
.foregroundColor(.white)
.font(Font.system(size: 12))
}
}
}
}
}虽然它确实呈现了一个功能性NavigationLink,但该徽章并没有像我所希望的那样右对齐显示。相反,它看起来像这样:

我知道我被HStack中的一些东西挂住了,但我不确定是什么。如何使类别标题文本占据行的大部分,并使徽章在行中右对齐?
发布于 2021-01-16 04:48:38
SwiftUI不知道Circle应该有多大,所以Spacer什么也不做。你应该为它设置一个固定的框架。
struct ContentView: View {
var body: some View {
List {
ForEach(0..<2) { categoryIndex in
let title = "Logins"
NavigationLink(destination: Text("Hi")) {
HStack(alignment: .center) {
Text(title)
Spacer()
ZStack {
Circle()
.foregroundColor(.gray)
.frame(width: 25, height: 25) // here!
Text("5")
.foregroundColor(.white)
.font(Font.system(size: 12))
}
}
}
}
}
}
}结果:

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