LoginSignup
4
3

More than 1 year has passed since last update.

【SwiftUI】リストにスワイプアクションを追加する

Posted at

はじめに

iOS15からswipeActionsというメソッドが追加されていました。
以下のような機能を実装することができます。
Simulator Screen Recording - iPhone 14 - 2022-12-30 at 21 26 13

実装

import SwiftUI

struct ContentView: View {
    var body: some View {
        List {
            Text("サンプル")
                .swipeActions(edge: .trailing, allowsFullSwipe: true) {
                    Button {
                        print()
                    } label: {
                        Text("削除")
                    }
                    .tint(.red)
                }
                .swipeActions(edge: .leading, allowsFullSwipe: true) {
                    Button {
                        print()
                    } label: {
                        Text("お気に入り")
                    }
                    .tint(.yellow)
                }
        }
    }
}

解説

edge

edgeは以下の指定ができます

.trailing 左方向にスワイプした時に表示
.leading 右方向にスワイプした時に表示

allowsFullSwipe

allowsFullSwipeはBoolでの指定です。
trueを指定すると、スワイプを長めにすると実行されます。
falseを指定すると、削除を押さないと実行されません。

true false
simulator_screenshot_79BE90E7-187D-45F5-B80F-829A5B3E2B35 simulator_screenshot_1971A2D2-CFCE-43AE-A75B-EADC28DCFAC9

content

おそらくButtonのみ有効です。
他のコンポーネントも指定できますが、機能しません。

色の変更

tintで色を変更することができます。

.swipeActions(edge: .trailing, allowsFullSwipe: false) {
    Button {
        print()
    } label: {
        Text("削除")
    }
+   .tint(.red)
}

simulator_screenshot_34251ABA-EE7E-4FD5-80A5-27DFD49CBF37

複数のボタンの配置

content内にButtonを複数配置するだけです

.swipeActions(edge: .trailing, allowsFullSwipe: false) {
    Button {
        print()
    } label: {
        Text("お気に入り")
    }
    .tint(.yellow)
    
    Button {
        print()
    } label: {
        Text("削除")
    }
    .tint(.red)
}

simulator_screenshot_AE5FF865-6CB2-4715-9288-429631354CC4

おわり

これは便利ですねー

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3