Adding shapes in List row of SwiftUI

╄→гoц情女王★ 提交于 2020-07-09 08:37:33

问题


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

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


回答1:


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

So the solution can be like following

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

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



回答2:


Some views in SwiftUI fill all available space. Such views are shapes, colors, spacers, dividers, and GeometryReader.

Your Circle is a shape and it behaves similarly like a Spacer (in terms of filling space).

If you replace Circle with an image of a circle it will work:

ForEach(people, id: \.self) { person in
    HStack {
        Image(systemName: "circle.fill")
            .imageScale(.large)
        Spacer()
        VStack {
            Text("\(person)")
        }
    }
}


来源:https://stackoverflow.com/questions/62717688/adding-shapes-in-list-row-of-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!