IOS - How to create TableView with horizontal scrollable lists
- SwiftUI
In swiftUI, you can use the power of Stack
s and ScrollView
alongside with List
(if you want):
struct ContentView: View {
var verticalData = 0...3
var horizontalData = 0...15
var body: some View {
List(self.verticalData, id: \.self) { vData in
ScrollView(.horizontal) {
HStack(spacing: 16) {
ForEach(self.horizontalData, id: \.self) { _ in
Circle()
.foregroundColor(.blue)
.frame(width: 40, height: 40, alignment: .center)
}
}
}
}
}
}
In this example I used a List
for vertical data and a horizontal ScrollView
containing a HStack
(Horizonl stack) of circles.
- Example
The following code is the the only code to reproduce a view exactly like your illustration (4 years later on iPhone Xs):
struct CircleView: View {
var body: some View {
Circle()
.foregroundColor(.blue)
.frame(width: 80, height: 80, alignment: .center)
}
}
struct RowView: View {
var body: some View {
ScrollView(.horizontal) {
HStack(spacing: 16) {
VStack(alignment: .leading, spacing: 4) {
Text("Label")
Text("Some text here")
}
ForEach(0...15, id: \.self) { _ in
CircleView()
}
}
.padding(16)
}
}
}
struct ContentView: View {
var body: some View {
List {
ForEach(0...3, id: \.self) { _ in
RowView()
}.listRowInsets(EdgeInsets())
}
}
}
- Result
Using UIScrollView
may require heavy effort if there are large amount of UI elements inside each scrollview because you have to instantiate all those upfront. A better solution is to define your custom UITableViewCell
which has its own UITableView
but rotated in 90 degree for horizontal scrolling. UI elements inside will be created only when they need to be shown by using dequeueReusableCellWithIdentifier:forIndexPath:
. Please see some sample code on how to create a 90 degree rotated table view:
iPhone Tableview Use Cells in Horizontal Scrolling not Vertical
Use a UITableView
and add a UICollectionView
to your reusable tableView cell. UICollectionView
works similar to UITableView
in that the "items" (like cells) are reusable and instantiated only when they will appear on screen. I did a quick google search for tutorials and found UICollectionView in UITableViewCell. Check that out and a few other StackOverflow questions regarding design and you should be golden.
You can use a ScrollView to put inside your tableview and set the values "Direction lock enabled" and "Paging Enabled" to true for the scrollview.