はじめに
tableViewのcellに配置したlabelや画像の値を取り出したいけど、delegateは使いたくないという時に行ったコーディングのメモです。ググったらいろんな方法がありましたが、めんどくさそうだったので自分なりにコーディングしてみました。
処理の内容
customTableViewにimageViewとlabelを配置
⬇︎
imageViewがtappされた時にlabelの値を取得
⬇︎
labelの値が取得できたら画面遷移する
ViewControllerでの記述
細かいところは省きます。とりあえず最初はこんな感じでコードを書いていました。
ViewController.swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
let bounds = cell.bounds
cell.bounds.size.width = tableView.bounds.size.width
cell.imageView.frame = CGRect(x: 0, y: 0, width: bounds.size.height, height: bounds.size.height)
cell.imageView.isUserInteractionEnabled = true
cell.imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector("ACTION")))
return cell
}
取得できない訳
・まずselectorに引数を付加できないからcellの特定ができなくてlabelの値がバラバラになる
・eventによって振り分ける作業がselectorではできない
・そもそもcell固有の値を持っているのはTableViweCellクラスだから値が取得しずらい
とりあえず簡単に取得するために
・imageViewの上に透明なbuttonを配置
・TableViewCellクラスでbuttonのtouchDownイベントを処理して、ViewControllerに値を送る
・ViewControllerクラスではbuttonのイベントをtouchUpにして値を受け取り、画面遷移
TableViewCellでの記述
TableViewCell.swift
class TableViewCell: UITableViewCell {
let imageView = UIImageView()
let button = UIButton()
let label = UILabel()
override func awakeFromNib() {
super.awakeFromNib()
self.contentView.addSubView(imageView)
self.contentView.addSubview(label)
imageView.addSubView(button)
//touchDownでViewControllerに値を送る
button.addTarget(self, action: #selector(downAction), for: .touchDown)
}
@objc func downAction() {
if let str = profileLabel.text {
ViewController.text = str
}
}
}
ViewController変更点
ViewController.swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
let bounds = cell.bounds
cell.bounds.size.width = tableView.bounds.size.width
cell.imageView.frame = CGRect(x: 0, y: 0, width: bounds.size.height, height: bounds.size.height)
//追加
cell.button.frame = CGRect(x: 0, y: 0, width: bounds.size.height, height: bounds.size.height)
cell.button.backgroundColor = UIColor.clear
cell.button.addTarget(self, action: #selector(upAction), for: .touchUpInside)
//削除
//cell.imageView.isUserInteractionEnabled = true
//cell.imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector("ACTION")))
return cell
}
@objc func upAction() {
if let str = ViewController.str {
print("ViewController:\(str)")
self.performSegue(withIdentifier: "goNext", sender: nil)
} else {
print("error")
}
}
これで無事成功!
最後に
親Viewの検知を有効にしないと子viewの検知もできなくなるのでtrueに
ViewController.swift
cell.imageView.sUserInteractionEnabled = true