iosswiftswiftuiswiftui-list

How to make List reversed in SwiftUI


I'm new in SwiftUI, trying to make something like reverse in Android LinearLayoutManager

messagesRecyclerView = view.findViewById(R.id.messagesRecyclerView);

manager = new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, true); // => true means reverse layout
messagesRecyclerView.setLayoutManager(manager);

in this case everything goes from bottom to top.

Everything useful what I can find is tableview reverse: Load tableview from bottom, scroll up (reverse tableview) (iOS)

//In ViewDidLoad
conversationTableView.transform = CGAffineTransform(rotationAngle: -(CGFloat)(Double.pi));

//In cellForRowAtIndexPath
cell.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi));

but I don't know how to add it into List (seems like it just a wrapper around TableView). Another approach here: How to populate UITableView from the bottom upwards?

                List {
                    ForEach(itemsData.messages) { item in
                        ChatRow(item: item)
                    }
                    Text("Load more messages...")
                        .onAppear() {
                            print("Load more messages...")
                            self.itemsData.next()
                    }
                }

My assumption is to get something .onAppear or override methods to make this work.

Seems like SwiftUI too young to go that deep.

Another question: do they have an API to programmatically scroll in List?

Hope I'm not duplicating any questions.

Using it for anonymous chat app https://en.lonje.com/


Solution

  • There is a trick on UITableView that you flip the table and each cell. So it appears to be filling from bottom. You can do this trick in SwiftUI too:

    Fully Working Demo:

    struct ContentView: View {
        @State private var ids = [String]()
    
        var body: some View {
            ZStack {
                List(ids, id: \.self) { id in
                    Text(id)
                        .scaleEffect(x: 1, y: -1, anchor: .center) // 👈 Flip list items here
                }
                .scaleEffect(x: 1, y: -1, anchor: .center) // 👈 Flip the list itself here
                
                Button("Touch") {
                    self.ids.append(UUID().uuidString)
                }
            }
        }
    }