LoginSignup
4
6

More than 5 years have passed since last update.

UITableViewCellのタップ位置によって処理を変更する

Last updated at Posted at 2018-08-23

やりたいこと

・UITableViewの各Cellタップ時に詳細画面表示
・ただしCell内の画像タップ時には画像の拡大表示
スクリーンショット 2018-08-23 12.33.42.png

実装

ViewController.swift
var items: Array<Item>
struct Item{
    var text: String
    var imgUrl: String
}

// いつものtableViewタップ時処理
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // 詳細画面表示処理(省略)
}

// Cell設定
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell

    // テキストとか画像の設定(省略)

    // タップ検知のためisUserInteractionEnabledをtrueに
    // ※親Viewもすべてtrueじゃないと効かないっぽい
    cell.isUserInteractionEnabled = true
    // タップ時イベント設定
    cell.imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageViewTapped)))

    // タップ時処理で使用するためrowをtagに持たせておく
    cell.imageView.tag = indexPath.row

    return cell
}

// ImageViewタップ時のイベント
func imageViewTapped(sender:UITapGestureRecognizer){
    // URL取得
    var strUrl:String? = nil
    if let row = sender.view?.tag {
        strUrl = items[row]?.imgUrl
    }

    // 画像拡大表示処理(省略)
}

ハマりどころ

UITapGestureRecognizerでタップ時イベント設定しても動かない!なんで!
親Viewまで全部isUserInteractionEnabledをtrueにすることで解決。
ちゃんとやればdidSelectRowAtより優先されるっぽい。

イベント処理からだと何行目のCellなのかわからない!たすけて!
とりあえずViewは取れるからtagにindexPath.row入れて解決したけど、
もうちょい綺麗に取れないかなぁ

4
6
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
6