LoginSignup
5
3

More than 3 years have passed since last update.

[SwiftUI]リスト表示のセルにボタンが配置できない問題とその解決策

Posted at

いわゆる、UITableViewCellの上にUIButtonを置くような事がしたい場合にSwiftUIでどのように記述すれば良いでしょうか。

struct ContentView: View {
    var body: some View {
        List {
            Group {
                HStack {
                    Text("Tap ME!! →")
                    Button(action: {
                        print("tap!!")
                    }, label: {
                        Text("Button")
                    })
                }
            }
        }
    }
}

このように、Listの中でButtonを書けば良さそうです。では実行してみましょう。

Screen Shot 2019-10-08 at 2.10.06.png

レイアウトは良さそうですが、ボタンが黒色ですね。
もうお気づきかと思いますが、Listの中で宣言するButtonは選択可能なCellを表示することを表現します。
同様に、複数のButtonが存在してもセルをタップした際に全てのボタンが反応するセルになってしまいます。

セル内にボタン(っぽいもの)を配置したい場合は、


struct ContentView: View {
    var body: some View {
        List {
            Group {
                HStack {
                    Text("Tap ME!! →")
                    Text("Button").onTapGesture {
                        print("tap!!")
                    }
                }
            }
        }
    }
}

このように、onTapGestureなどで強制的に反応するようにしてあげれば良いです。

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