SwiftUI:水平堆叠重叠元素吗?

时间:2020-11-10 15:41:12

标签: ios swiftui

我想水平堆叠重叠的元素,像这样:

enter image description here

这是我尝试过的:

struct StackedElementsView: View {
    let colors: [Color] = [.red, .blue, .purple]
    
    var body: some View {
        HStack {
            ZStack {
                ForEach(0..<colors.count) { i in
                    ZStack(alignment: .leading) {
                        colors[i]
                            .clipShape(Circle())
                            .frame(width: 44, height: 44)
                    }
                    .offset(x: CGFloat(i) * 25)
                }
            }
            .padding(.leading, 24)
            Color.purple
                .frame(width: 100, height: 44)
            Spacer()
        }
        .padding(.vertical, 8)
    }
}

struct StackedElementsView_Previews: PreviewProvider {
    static var previews: some View {
        StackedElementsView()
    }
}

我对此有疑问,紫色矩形与圆圈重叠,我不知道为什么。

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

.offset仅更改视图的绘制位置,但不更改框架,这就是矩形向左绘制超出您预期的原因。

解决此问题的一种方法是在矩形中添加适当的前导填充:

Color.purple
    .frame(width: 100, height: 44)
    .padding(.leading, CGFloat(colors.count - 1) * 25)

替代解决方案

不是使用.offset,而是使用Color.clear中的HStack视图来提供所需的间距:

ForEach(0..<colors.count) { i in
    ZStack(alignment: .leading) {
        HStack(spacing: 0) {
            Color.clear
                .frame(width: CGFloat(i) * 25, height: 44)
            colors[i]
                .clipShape(Circle())
                .frame(width: 44, height: 44)
        }
    }
}

答案 1 :(得分:1)

这将是一个更直观的解决方案。您可以改用负间距,并且仅使用HStack

enter image description here

struct StackedElementsView: View {
    let colors: [Color] = [.red, .blue, .purple]
    
    var body: some View {
        HStack {
            HStack(spacing: -25) {
                ForEach(0..<colors.count) { i in
                    colors[i]
                        .clipShape(Circle())
                        .frame(width: 44, height: 44)
                }
            }
            
            Color.purple
                .frame(width: 100, height: 44)
            Spacer()
        }
        .padding(.leading, 24)
        .padding(.vertical, 8)
    }
}