简体   繁体   中英

List that scrolls to certain row when button pressed in SwiftUI app

In a SwiftUI app, I'm trying to create a list that automatically scrolls to the next row when a button is pressed.

Apparently, this functionality isn't currently possible with a SwiftUI List, but is with UITableView using the scrollToRowAtIndexPath method as mentioned in part #3 of this answer https://stackoverflow.com/a/58830883/11698443 This answer is well explained but doesn't suggest how to implement what they described as the best solution.

Below is some example code of how the list could look in SwiftUI. The goal would be for the button to be pressed and then for the list to scroll to the next row. I think the solution would need to interface with UIKit in order for it to work. It would be awesome if someone could figure out how to do this in the cleanest possible way. It's unfortunate that this can't be done using all SwiftUI.

Thanks in advance to anyone who thinks that they can solve this problem.

import SwiftUI

struct ScrollingList: View {
    var body: some View {
        List(0 ..< 10) { item in
            VStack {
                Text("\(item)")

                Button(action: {}) {
                Text("Scroll To Next Item")
                }
            }
            .frame(height: 500)
            .background(Color.blue)
        }
    }
}

check out this nifty library, https://github.com/siteline/SwiftUI-Introspect . with it you can do this:

import Introspect

List {
  Text("some")
  Text("list")
}.introspectTableView { tableView in
          tableView.scrollToRowAtIndexPath(<#IndexPath#>, atScrollPosition: <#UITableView.ScrollPosition#>, animated: <#Bool#>)
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM