Implementing ScrollView & List
Published by @SoNiceInfo at 6/25/2020
Use ScrollView and List to implement scrolling.
ScrollView
When you call ScrollView, you specify the scrolling direction, visibility of the scrollbar and its content.
For horizontal scrolling, use .horizontal and struct the contents with HStack.
For vertical scrolling, use .vertical and struct the contents with VStack.
In this example, EmojiTile views are structed in HStack so that it can be scrolled by ScrollView.
The demo shows the horizontal scrolling.
List
List, as the name implies, allows you to implement list-style scrolling.
As shown in the following code, you can list the data with passing the data.
The following will list animals with multiple animal information.
If the data conforms to the Identifiable protocol, SwiftUI can follow the movement of the list elements when they are added or removed.
struct Animal: Identifiable {
var id: Int
let name: String
}
List (animals) { animal in
Text(animal.name)
}This example uses Text directly for each list item。
The demo shows the scrolling of the list.
//
// ContentView.swift
//
import SwiftUI
struct ContentView: View {
var body: some View {
VStack () {
Spacer()
ScrollView(.horizontal, showsIndicators: false) {
HStack {
EmojiTile(text: "😀", color: .blue)
EmojiTile(text: "😉", color: .green)
EmojiTile(text: "😊", color: .purple)
EmojiTile(text: "😀", color: .blue)
EmojiTile(text: "😉", color: .green)
EmojiTile(text: "😊", color: .purple)
EmojiTile(text: "😀", color: .blue)
EmojiTile(text: "😉", color: .green)
EmojiTile(text: "😊", color: .purple)
}
}
Spacer()
List() {
Text("Hoge")
Text("Fuga")
}
Spacer()
}
}
}
struct EmojiTile: View {
var text: String
var color: Color
var body: some View {
Text(text)
.font(.custom("Emoji", size: 50))
.padding(50)
.background(color)
.cornerRadius(10)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}References
ScrollView - SwiftUI | Apple Developer DocumentationList - SwiftUI | Apple Developer Documentation

