やりたいこと
・UITableViewの各Cellタップ時に詳細画面表示
・ただしCell内の画像タップ時には画像の拡大表示
実装
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入れて解決したけど、
もうちょい綺麗に取れないかなぁ