简体   繁体   中英

How can I draw a line between Shapes in SwiftUI?

I have HStacks in a ScrollView, and in the HStacks there are circles and texts. How could I draw a line between the circles? (It's a bus's route)

在此处输入图像描述

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

Create one struct for cell (which is HStack in your code).

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

在此处输入图像描述

A variation on the answer by Raja would be to use 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")
    }
}

模拟器视图...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM