【SwiftUI】Listにスワイプアクション(swipeActions)を実装する方法!

この記事からわかること

  • Swift UIList構造体swipeActions実装する方法
  • HorizontalEdge種類
  • 複数ボタンを設置するには?
  • onDeleteを使った削除ボタンの実装
  • 背景色変更方法

index

[open]

\ アプリをリリースしました /

みんなの誕生日

友達や家族の誕生日をメモ!通知も届く-みんなの誕生日-

posted withアプリーチ

swipeActions(edge:allowsFullSwipe:content:)

公式リファレンス:swipeActions(edge:allowsFullSwipe:content:)

SwiftUIでList構造体を使用してリスト表示している行にスワイプアクションを追加するにはswipeActionsを使用します。

func swipeActions<T>(
    edge: HorizontalEdge = .trailing,
    allowsFullSwipe: Bool = true,
    content: () -> T
) -> some View where T : View

引数

HorizontalEdge

スワイプする方向は列挙型HorizontalEdgeの値で指定します。左側と右側を選択できます。

@frozen  enum HorizontalEdge {
  case leading // 左側
  case trailing  // 右側
}

スワイプアクションを実装する方法

スワイプアクションを実装するには表示させる行ごとにswipeActionsモディファイアを呼び出します。以下はList表示させるデータをForEachを使って回している場合の例です。

List{
  ForEach(notification){ notice in
      RowNotificationView(notice: notice) // 行ビュー 
      .swipeActions(edge: .trailing) {
          Button(role: .destructive) {
              print("削除するよ")
          } label: {
              Image(systemName: "trash")
          }
      }
  }
}

表示させるcontentButtonを設置することでタップ時に処理を実行できるようにすることができます。またButtonrole属性を付与することでdestructiveなら背景色が赤色になります。

複数のボタンを設置する

スワイプした際のボタンは複数設置することも可能です。その場合はcontent内にビューをそのまま複数指定すればOKです。

.swipeActions(edge: .trailing) {
    Button(role: .destructive) {
        print("削除するよ")
    } label: {
        Image(systemName: "trash")
    }
    Button {
        print("Swift")
    } label: {
        Image(systemName: "swift")
    }
}

背景色を指定する

スワイプして表示されるボタンの背景色を変更するにはtintモディファイアを使用します。

.swipeActions(edge: .trailing, allowsFullSwipe: false) {
    Button(role: .none) {
      print("Swift")
    } label: {
        Text("返却")
    }.tint(Color.thema1)
}

onDeleteを使ったスワイプ削除ボタン

onDeleteを使用することで簡単にスワイプ時の削除ボタンを実装することもできます。

ForEach(notification){ notice in
    RowNotificationView(notice: notice)
}.onDelete(perform: { index in
    manager.removeNotificationRequest(id:notification[index.first!].id)
    $notification.remove(atOffsets: index)
    isAlert = true
})

まだまだ勉強中ですので間違っている点や至らぬ点がありましたら教えていただけると助かります。

ご覧いただきありがとうございました。

searchbox

スポンサー

ProFile

ame

趣味:読書,プログラミング学習,サイト制作,ブログ

IT嫌いを克服するためにITパスを取得しようと勉強してからサイト制作が趣味に変わりました笑
今はCMSを使わずこのサイトを完全自作でサイト運営中〜

New Article

index