ScrollView trong SwiftUI
1. Vertical ScrollView
ScrollView {
VStack {
ForEach(0..<50) { i in
Text("Item \(i)")
.padding()
}
}
}2. Horizontal ScrollView
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 16) {
ForEach(items) { item in
ItemCard(item: item)
}
}
.padding(.horizontal)
}3. Hide Indicators
ScrollView(showsIndicators: false) {
// Content
}4. Scroll Position (iOS 17+)
struct ScrollableList: View {
@State private var scrollPosition: Int?
var body: some View {
ScrollView {
LazyVStack {
ForEach(0..<100) { index in
Text("Item \(index)")
.id(index)
}
}
}
.scrollPosition(id: $scrollPosition)
Button("Go to 50") {
scrollPosition = 50
}
}
}5. ScrollViewReader
struct ScrollToView: View {
var body: some View {
ScrollViewReader { proxy in
ScrollView {
Button("Go to Bottom") {
withAnimation {
proxy.scrollTo("bottom")
}
}
ForEach(0..<100) { i in
Text("Item \(i)")
.id(i)
}
Text("Bottom")
.id("bottom")
}
}
}
}6. Carousel
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 16) {
ForEach(cards) { card in
CardView(card: card)
.frame(width: 300, height: 200)
}
}
.padding(.horizontal)
}
.scrollTargetBehavior(.paging) // iOS 17+📝 Tóm tắt
| Modifier | Mục đích |
|---|---|
.horizontal | Scroll ngang |
showsIndicators: false | Ẩn scrollbar |
ScrollViewReader | Programmatic scroll |
.scrollPosition | Track/set position |
Last updated on