【问题标题】:How can I draw a line between Shapes in SwiftUI?如何在 SwiftUI 中的形状之间画一条线?
【发布时间】:2020-12-09 17:16:15
【问题描述】:

我在 ScrollView 中有 HStack,在 HStack 中有圆圈和文本。我怎么能在圆圈之间画一条线? (这是公共汽车的路线)

ForEach(stations, id: \.id) { station in
                
                HStack{
                    Spacer().frame(width: 20)
                    Circle()
                        .stroke(Color.black,lineWidth: 4)
                        .frame(width: 10, height: 10)
                    Spacer().frame(width: 20)
                    
                    Text(station.name)
                    
                    Spacer()
                    
                    if station.id > 0 {
                        Text(String(station.id))
                    }
                    
                    
                    let time = getNextDepartureTime(id: station.id)
                    
                    Text("\(time.hour):\(time.minute)")
                    
                    Spacer().frame(width: 20)
                    
                }
                
            }

【问题讨论】:

  • 你会展示你的代码吗?
  • 已添加,抱歉。

标签: ios swift iphone swiftui


【解决方案1】:

为单元格创建一个结构(在您的代码中是 HStack)。

// Content HStack cell view
struct ContentCellView: View {
    var isLast: Bool = false
    var body: some View {
        VStack(alignment: HorizontalAlignment.leading, spacing: 0) {
            HStack {
                Image(systemName: "message.circle").frame(width: 30)
                Text("Route")
                Spacer()
                Text("Time")
            }
            if !isLast {
                Rectangle().fill(Color.blue).frame(width: 1, height: 14, alignment: .center).padding(.leading, 15.5)//.offset(y: -10)
            }
        }
    }
}

struct ContentView: View {
    var body: some View {
        ScrollView{
            VStack(spacing: 0){
                ForEach((1...10).reversed(), id: \.self) {
                    ContentCellView(isLast: $0 == 1) // isLast for not showing last line in last cell
                }
            }
        }.padding()
    }
}

【讨论】:

  • 聪明。 只要 OP 没问题,行之间的间隙就是一个很好的解决方案。你选择蓝色是为了让你的线条更容易看到吗?
  • 是的,我使用蓝色进行演示,您可以根据需要进行更改,也可以设置空间、填充、大小等。
【解决方案2】:

Raja 的答案的一个变体是使用 ZStack...

ZStack {
    HStack {
        Rectangle().frame(width: 2, height: 22, alignment: .center).padding(.leading, 9)
        Spacer()
    }
    HStack {
        Image(systemName: "message.circle")
        Text("Route")
        Spacer()
        Text("Time")
    }
}

【讨论】:

    猜你喜欢
    • 2020-03-31
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    相关资源
    最近更新 更多