[英]How to implement delete and move function using SwiftUI framework
Xcode 11 GM現在提供了您所引用的方法。 您可以像這樣使用它們。
刪除元素
TLDR:
.onDelete{offsets in
self.array.remove(atOffsets: offsets)
完整代碼(可以復制粘貼):導入SwiftUI
struct MyTableView : View {
@State var array=[1,2,3,4,5]
var body: some View {
List{
ForEach(array,id:\.self){element in
Text("\(element)")
}
.onDelete{offsets in
self.array.remove(atOffsets: offsets)
}
}
}
}
struct MyTableView_Previews : PreviewProvider {
static var previews: some View {
MyTableView()
}
}
運動元素
.onMove { (offsets, targetOffset) in
self.array.move(fromOffsets: offsets, toOffset: targetOffset)
}
這些方法是Swift 5.1標准庫的一部分,Apple會在以后的Xcode Beta中提供該方法。 同時,您可以使用以下擴展名:
extension Array {
mutating func remove(atOffsets offsets: IndexSet) {
let suffixStart = halfStablePartition { index, _ in
return offsets.contains(index)
}
removeSubrange(suffixStart...)
}
mutating func move(fromOffsets source: IndexSet, toOffset destination: Int) {
let suffixStart = halfStablePartition { index, _ in
return source.contains(index)
}
let suffix = self[suffixStart...]
removeSubrange(suffixStart...)
insert(contentsOf: suffix, at: destination)
}
mutating func halfStablePartition(isSuffixElement predicate: (Index, Element) -> Bool) -> Index {
guard var i = firstIndex(where: predicate) else {
return endIndex
}
var j = index(after: i)
while j != endIndex {
if !predicate(j, self[j]) {
swapAt(i, j)
formIndex(after: &i)
}
formIndex(after: &j)
}
return i
}
func firstIndex(where predicate: (Index, Element) -> Bool) -> Index? {
for (index, element) in self.enumerated() {
if predicate(index, element) {
return index
}
}
return nil
}
}
他們使用了Array的自定義擴展或尚未公開的某些版本的Swift。 我實現的解決方法是:
刪除
func delete(at offsets: IndexSet) {
if let first = offsets.first {
store.rooms.remove(at: first)
}
}
移動
func move(from source: IndexSet, to destination: Int) {
if let first = source.first {
store.rooms.swapAt(first, destination)
}
}
移動功能有效,但是動畫效果不如WWDC 2019上的視頻動畫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.