我正在尋找如何水平對齊串列中的專案,專案從最后一個專案或右邊緣開始,然后從那里向左。
例如,對于 1-20 的串列,我希望在螢屏左邊緣顯示專案 1-5,專案 20 是最右邊的專案,就在螢屏邊緣。可以在下面顯示此影像(它不是正在運行的解決方案,而是顯示所需效果的人為影像)。

如何在 SwiftUI 中做到這一點?
HStack 將簡單地水平居中。HStack 似乎沒有我可以控制的水平對齊方式。
滾動視圖中的 HStack 允許我到達最右邊的專案,但仍然從第一個專案或串列的最左邊開始。
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Divider()
// the HStack just tries to fit everything within the width of the view,
// without anything going "offscreen"
HStack(spacing: 10) {
ForEach(1..<21) { index in
Text("\(index)")
}
Spacer()
}
Divider()
// placing the HStack within a ScrollView does allow elements to go offscreen,
// but the list starts at 1 and goes offscreen at 16 on the right
// I am looking for how to "anchor" the list on the right edge instead,
// with elements 1 through 5 being displayed off the left edge of the screen,
// and the right-most element being 20, directly on the right edge of the screen
ScrollView(.horizontal) {
HStack(spacing: 10) {
ForEach(1..<21) { index in
Text("\(index)")
}
}
}
.frame(height: 100)
Divider()
// are there any other ways to achieve my desired effect?
}
}
}
uj5u.com熱心網友回復:
如果我正確理解問題,您似乎需要ScrollViewReader:
// Define array for your label
var entries = Array(0...20)
ScrollView(.horizontal) {
ScrollViewReader { reader in
HStack(spacing: 10) {
ForEach(entries, id: \.self) { index in
Text("\(index)")
}.onAppear {
// Here on appear scroll go to last element
reader.scrollTo(entries.count - 1)
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/452654.html
上一篇:將SwiftUI與@AppStorage和動態函式呼叫一起使用
下一篇:首次出現時顯示所選專案單元格
