In SwiftUI how can I have a View exceed its parents frame/boundary in a List?

Viewed 41

Consider the following code:

import SwiftUI

struct ContentView: View {
  private var listContent: [String] = ["This", "is", "a", "placeholder", "list"]
  
  var body: some View {
    List {
      ForEach(listContent, id: \.self) { entry in
        listElement(text: entry)
      }
    }
  }
}

struct listElement: View {
  @State var text: String
  
  var body: some View {
    Section() {
      HStack {
        Rectangle()
          .fill(.green)
          .frame(width: 30, height: nil)
        Text(text)
      }
      .listRowInsets(EdgeInsets())
    }
  }
}

which generates this

code

I would like to add additional markers to the left of each List element and/or section, like this (mockup):

mockup

I have the data that describes the width of the green bars leading into the list elements on the child and parent element. Coming from web development I expect to do something like a child element having negative margin and is thus exceeding its parents container. However I could not get it to work with SwiftUI's padding. Is there a way to do this?


For example I have tried the following modification to the previously mentioned listElement:

  var body: some View {
    Section() {
      HStack {
        Rectangle()
          .fill(.red)
          .frame(width: 30, height: 10)
          .padding(.leading, -20)
          .zIndex(9999)
        Rectangle()
          .fill(.green)
          .frame(width: 30, height: nil)
        Text(text)
      }
      .listRowInsets(EdgeInsets())
    }
  }

which results in:

enter image description here

The red rectangle overflow is hidden. I've tried pushing it to the top with the dreaded zIndex hack but it doesn't work. Even setting the Lists .scrollContentBackground to .hidden and the .background to .clear doesn't show the red Rectangle. I need the overflow to be visible.

0 Answers
Related