寒川アクアブログ

美容師しながらアプリ開発していて水草が趣味の私のブログです

【Swift4】TableViewのCellのイメージをタップした時のrow取得

TableViewのCellのデフォルトで左に表示できるイメージをタップした時に何かする

セルにイメージを設定すると、Content ViewにImage Viewが追加されます。

セルの情報を決めるメソッド内で、タップジェスチャーを設定します。
ストーリーボードから設定すると、1番目のセルにしかジェスチャーが付かないようでした。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellName,for: indexPath)

    if cell.imageView?.gestureRecognizers?.count == 0 { 
            //gestureを設定
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.iconTapped(_:)))
        cell.imageView?.addGestureRecognizer(tapGesture)
        cell.imageView?.isUserInteractionEnabled = true

    }
    return cell
}

上記で、タップされた時に呼ばれる、iconTapped()というメソッドを定義しました。

@IBOutlet weak var tableView: UITableView!
 
func iconTapped(_ sender: UITapGestureRecognizer) {   
    let gr = sender as! UIGestureRecognizer
    let tappedLocation = gr.location(in: tableView)
    let tappedIndexPath = tableView.indexPathForRow(at: tappedLocation)
    let tappedRow = tappedIndexPath?.row
}

これでセルのrowが取得できました。
他に良いやり方もありそうなものですが、これで目的はとりあえず達成されました。