Reputation: 682
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)
}
}
}
Upvotes: 0
Views: 351
Reputation: 168
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#>)
}
Upvotes: 1