我在 SwiftUI 中有一個 HStack 圓圈,圓圈的數量是根據陣列的長度確定的,如下所示:
@State var myArr = [...]
...
ScrollView(.horizontal) {
HStack {
ForEach(myArr) { item in
Circle()
//.frame(...)
//.animation(...) I tried this, it didn't work
}
}
}
然后我有一個按鈕,將一個元素附加到這個陣列,有效地在視圖中添加一個圓圈:
Button {
myArr.append(...)
} label: {
...
}
該按鈕按預期作業,但是,添加到視圖中的新圓圈顯得非常突然,并且看起來不連貫。我怎樣才能以任何方式對此進行影片處理?也許它從側面滑入,或者從一個非常小的圓圈增長到它的正常大小。
uj5u.com熱心網友回復:
您缺少過渡,這就是您要尋找的內容:
struct ContentView: View {
@State private var array: [Int] = Array(0...2)
var body: some View {
ScrollView(.horizontal) {
HStack {
ForEach(array, id:\.self) { item in
Circle()
.frame(width: 50, height: 50)
.transition(AnyTransition.scale)
}
}
}
.animation(.default, value: array.count)
Button("add new circle") {
array.append(array.count)
}
Button("remove a circle") {
if array.count > 0 {
array.remove(at: array.count - 1)
}
}
}
}
uj5u.com熱心網友回復:
自動滾動到最后一個圓圈的版本:
struct myItem: Identifiable, Equatable {
let id = UUID()
var size: CGFloat
}
struct ContentView: View {
@State private var myArr: [myItem] = [
myItem(size: 10),
myItem(size: 40),
myItem(size: 30)
]
var body: some View {
ScrollViewReader { scrollProxy in
VStack(alignment: .leading) {
Spacer()
ScrollView(.horizontal) {
HStack {
ForEach(myArr) { item in
Circle()
.id(item.id)
.frame(width: item.size, height: item.size)
.transition(.scale)
}
}
}
.animation(.easeInOut(duration: 1), value: myArr)
Spacer()
Button("Add One") {
let new = myItem(size: CGFloat.random(in: 10...100))
myArr.append(new)
}
.onChange(of: myArr) { _ in
withAnimation {
scrollProxy.scrollTo(myArr.last!.id, anchor: .trailing)
}
}
.frame(maxWidth: .infinity, alignment: .center)
}
.padding()
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/427588.html
