3

我正在开发我的第一个 SwiftUI 应用程序,并希望在其中显示一个List类别,并带有一个指示该类别中项目数量的徽章。类别的标题将在左侧,徽章将在行上右对齐。该列表将由NavigationLinks 组成,因此点击一个将进一步深入到视图层次结构中。我为渲染NavigationLinks 而编写的代码如下所示:

        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,但不确定是什么。我如何获得它,以便类别标题 Text 占据该行的大部分,并且该行中的徽章右对齐?

4

1 回答 1

3

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))
                        }
                    }
                }
            }
        }
    }
}

结果:

于 2021-01-15T20:48:38.367 回答