本文介绍了在 SwiftUI 的列表行中添加形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个列表视图,其中的行如下所示:

I am trying to create a List View where rows looks like this:

但是,我无法在前导侧对齐 Circle.尝试在 VStack 中使用 Spacer()HStack,它只是不起作用.这是我的代码及其输出.

However, I am unable to align the Circle on the leading side. Tried using Spacer(), HStack within VStack, it just doesn't work. Here's my code and its output.

struct PeopleView: View {

    let people = ["Adam", "James"]

    var body: some View {
        NavigationView {
            List {
                ForEach(people, id: .self) { person in
                    HStack {
                        Circle()
                        VStack {
                            Text("(person)")
                        }
                    }
                }
            }
            .navigationBarTitle("People", displayMode: .inline)
        }
    }
}

推荐答案

实际上,在这种情况下,您不需要形状本身,而只是作为一个蒙版来直观地呈现圆形文本.

Actually you don't need shape itself in this case, but only as a mask to visually present text in circle.

所以解决方案可以如下

HStack {
    Text(person.prefix(2).uppercased()).bold()
        .foregroundColor(.white)
        .padding()
        .background(Color.red)
        .mask(Circle())          // << shaping text !!

    Spacer()
    VStack {
        Text("(person)")
    }
}

这篇关于在 SwiftUI 的列表行中添加形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 03:34