SwiftUI:列表、NavigationLink 和徽章
SwiftUI: List, NavigationLink, and badges
我正在开发我的第一个 SwiftUI 应用程序,我想在其中显示 List
个类别,并带有一个标志,指示该类别中的项目数。类别的标题位于左侧,徽章位于行的 right-aligned。该列表将由 NavigationLink
组成,因此点击其中一个将进一步向下钻取到视图层次结构中。我编写的用于呈现 NavigationLink
s 的代码如下所示:
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
,但并未显示徽章 right-aligned,正如我所希望的那样。相反,它看起来像这样:
我知道我的 HStack
中有一些东西挂断了电话,但我不确定是什么。我如何才能使类别标题文本占据大部分行,并且行中有徽章 right-aligned?
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))
}
}
}
}
}
}
}
结果:
我正在开发我的第一个 SwiftUI 应用程序,我想在其中显示 List
个类别,并带有一个标志,指示该类别中的项目数。类别的标题位于左侧,徽章位于行的 right-aligned。该列表将由 NavigationLink
组成,因此点击其中一个将进一步向下钻取到视图层次结构中。我编写的用于呈现 NavigationLink
s 的代码如下所示:
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
,但并未显示徽章 right-aligned,正如我所希望的那样。相反,它看起来像这样:
我知道我的 HStack
中有一些东西挂断了电话,但我不确定是什么。我如何才能使类别标题文本占据大部分行,并且行中有徽章 right-aligned?
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))
}
}
}
}
}
}
}
结果: