5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【SwiftUI】Listに配置したButtonのタップ領域がセル全体になってしまう場合の対処法

Posted at

結論

Listのセル内にButtonを配置したところ、Buttonのタップ領域がセル全体になり困っていましたが
.buttonStyle(.plain)
を追加することで、正常に動作するようになりました。

環境

Xcode 14.1

内容

直したかったこと

ListにButtonを配置すると、セルのどこをタップしてもButtonのActionが実行されてしまい、ボタンとして機能しませんでした。

    var body: some View {
        List {
            HStack {
                Text("アイテム")
                Spacer()
                Button {
                    // タップ時の処理
                } label: {
                    Label("追加", systemImage: "plus")
                }
                .padding(10)
                .overlay(
                    RoundedRectangle(cornerRadius: 10)
                        .stroke(Color.blue, lineWidth: 1)
                )
            }
        }
        .listStyle(.plain)
        .padding(.vertical, 30.0)
        .scrollContentBackground(.hidden)
        .background(Color.gray)
    }

対応方法

.buttonStyle(.plain)を追加することで、セルの中でボタンとして動くようになりました。

    var body: some View {
        List {
            HStack {
                Text("アイテム")
                Spacer()
                Button {
                    print("タップ")
                } label: {
                    Label("追加", systemImage: "plus")
                }
                .padding(10)
                .overlay(
                    RoundedRectangle(cornerRadius: 10)
                        .stroke(Color.blue, lineWidth: 1)
                )
+               .buttonStyle(.plain)
            }
        }
        .listStyle(.plain)
        .padding(.vertical, 30.0)
        .scrollContentBackground(.hidden)
        .background(Color.gray)
    }

おわりに

とても簡単なことでしたが、同じように困っている方がいたらと思い記事にしました。

5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?