3

The array of items is ordered so that new items are at index 0.

I want the scroll behavior of the ScrollView completely reversed so the newest item 0 is shown at the bottom, and the user must scroll new items down to slide older items in from the top of the scrollview.

Old items are dynamically added when the last item in the array appears.

Here's what I have so far and it works, but the 180 rotation effect just seems inelegant. I feel like this is creative hackery and there just must be a better way.

import SwiftUI

struct MyReversedScrollView: View {
    @State var items: [Int]
    init() {
        _items = State(initialValue: Array(1...10))
    }
    var body: some View {
        ScrollView() {
            LazyVStack(spacing: 10) {
                ForEach(items, id: \.self) { item in
                    ItemView(item: item)
                        .zIndex(Double(items.count - item))
                        .onAppear {
                            if items.last == item {
                                items += Array((item+1)...(item+10))
                            }
                        }
                }
            }
        }
        .rotationEffect(.degrees(-180))
    }
}

struct MyReversedScrollView_Previews: PreviewProvider {
    static var previews: some View {
        MyReversedScrollView()
    }
}

struct ItemView: View {
    let item: Int
    var body: some View {
        Text(item.description)
            .frame(width: 100, height: 100)
            .border(Color.black)
            .rotationEffect(.degrees(-180))
    }
}
Alejandro
  • 7,290
  • 4
  • 34
  • 59
TD540
  • 1,728
  • 3
  • 14
  • 26
  • 1
    I’m pretty sure this is how you’d most easily do it in UIKit as well. So I don’t really see your problem tbh :P The only thing I’d change is add the item rotation when creating the list view so that the item view could possibly be used without the rotation if ever necessary – Mihai Fratu Apr 24 '21 at 07:10
  • 1
    Does this answer your question https://stackoverflow.com/a/58708206/12299030? – Asperi Apr 24 '21 at 08:48

1 Answers1

0

Instead of replacing items with another array, why don't you just append the extra items.

Try replacing:

 items += Array((item+1)...(item+10))

With:

 items.append(Array((item+1)...(item+10)))
mtz_federico
  • 107
  • 1
  • 9
  • Items aren't replaced here. `+=` already adds them to the array correctly. You also can't use `append(...)` to add an Array of Int's to an Array of Int's in Swift. My code example here is just a simpler simulation of what I'm actually doing, which is loading and adding 10 items into the array from an API, dynamically when last item appears. But this is irrelevant to my question which was about the inelegant rotation effect. – TD540 Apr 24 '21 at 05:07