The Util Designer
SwiftUI 使用swipeActions創建客製化滑動操作
xcode 13.4.1, swift 5.5, iOS 15.4
2022-08-28
在一些列表的App中,像email app中,可以右滑做封存,左滑做刪除的動作,SwiftUI在iOS 15提供了一個方法讓大家可以很方使的為List的Item做一些客製他的滑動操作。
1. 先使用List來顯示一個字符串的列表。
import SwiftUI

struct SwipeActionsExample : View {
    @State var list : [String] = ["One", "Two", "Three", "Four", "Five",
        "Six", "Seven", "Eight", "Nine", "Ten",
    "Apple", "Orange", "Banana"]
    var body: some View {
        List {
            ForEach(0..<list.count, id:\.self) { index in
                Text(list[index])
            }
        }
    }
}
2. 然後在每個Item加一個向左滑來顯示一個Delete的按鈕
import SwiftUI

struct SwipeActionsExample : View {
    @State var list : [String] = ["One", "Two", "Three", "Four", "Five",
        "Six", "Seven", "Eight", "Nine", "Ten",
    "Apple", "Orange", "Banana"]
    var body: some View {
        List {
            ForEach(0..<list.count, id:\.self) { index in
                Text(list[index])
                    .swipeActions(edge: .trailing) {
                        Button {
                            list.remove(at: index)
                        } label: {
                            Label("Delete", systemImage: "trash")
                        }
                        .tint(.red)
                    }
            }
        }
    }
}
3. swipeActions(edge: .trailing)就是把額外按鈕放在右邊,以下把trailing改成leading,就可以做成右滑動操作。

import SwiftUI

struct SwipeActionsExample : View {
    @State var list : [String] = ["One", "Two", "Three", "Four", "Five",
        "Six", "Seven", "Eight", "Nine", "Ten",
    "Apple", "Orange", "Banana"]
    var body: some View {
        List {
            ForEach(0..<list.count, id:\.self) { index in
                Text(list[index])
                    .swipeActions(edge:.leading) {
                        Button(role: .destructive) {
                            list.remove(at: index)
                        } label: {
                            Label("Delete", systemImage: "trash")
                        }
                        .tint(.red)
                    }
            }
        }
        .animation(.linear, value: list)
    }
    
}