skip to Main Content

When I use this block of code, I want ScrollView and ForEach views to expand when new items are added to ForEach view. But currently it just fills some space that is larger than the view inside ForEach block. How can I make it fill space for only views sizes inside ForEach block of code?

ScrollView {
    ForEach(files, id: .self) { item in
        HStack {
            Image("file")
            Text(item)
               .lineLimit(1)
                                    
             Spacer()
                                    
             Button {
                files.removeAll(where: { $0 == item })
             } label: {
                Image("close")
             }
        }
    }
}

I tried setting minWidth and maxWidth for scroll view. But that doesn’t seem to work

2

Answers


  1. I don’t really get what’s your issue with the scrollView filling all the available empty space but if you really need to fix the ScrollView height to the minimum you can add .fixedSize(horizontal: false, vertical: true) to your ScrollView content closure.

    .fixedSize will tell the view to resize to its optimal frame (most of the time the smallest possible), but the view expanding in SwiftUI is the default way (cause view will automatically resize looking at their neighbors) and I see no point in preventing the ScrollView from expanding, can you give more details about what you are trying to achieve?

    Result (before/after fixedSize) using your code with the scroll view in red and the foreach in blue

    enter image description here
    enter image description here

    Login or Signup to reply.
  2. id: .self needs to be changed to id: .someUniqueProperty

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search