0

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

zigmuntb
  • 15
  • 3
  • You need to clarify the question. For example, what you mean by each "expand", both for the desired and actual behaviour (horizontal or vertical?), what you mean by "fill space larger than the view" as it can't, etc. – flanker Jul 02 '23 at 20:11

2 Answers2

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

xfost
  • 111
  • 5
0

id: \.self needs to be changed to id: \.someUniqueProperty

malhal
  • 26,330
  • 7
  • 115
  • 133