2018/01/25

UITableViewCellのサブクラスのファイル作成

ストーリーボード上でカスタムセルのボタンからViewControlerに対してOutlet接続をしようとして下記エラーが発生

エラー内容

Outlet cannot be connected to repeating content

TableViewのCellは繰り返し使用されるオブジェクトであるため、
直接に親のUIViewControllerに対してOutlet接続することができない

解決策

UITableViewCellのサブクラスのファイル(下記の赤字以降を)を作成して、そちらとOutletを作成します。

具体的な作業

tableViewCell.swiftファイルを作成

//tableViewCellを作成
import UIKit

class tableViewCell: UITableViewCell {

@IBOutlet weak var button: UIButton!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

    
}

ストーリーボードの作業

・Identity Inspectorの修正(左から3番目)
UITableViewCellのClass -> tableViewCellにする

・Attributes Inspectorの修正(左から4番目)
Identifier -> tableViewCellにする

ViewContollerの作業

セルの再利用を設定する

    // セルの設定
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell",for: indexPath)
        
        return cell
    }

  @IBAction func tappedButton(sender: AnyObject) {
        print("Tap")
    }

ボタンの接続

上記のケースは
・tableViewCell.swiftとボタンのoutlet接続
・ViewController.swiftとボタンをAction接続

としています。


お知らせ

ヒヨコ歩数計という歩きながらヒヨコが育っていくアプリを作って、いろんな方に結構使ってもらっています。
RealmSwift, Admobの動画・インステ・バナー広告、UICollectionView、iOS-Charts、UITableViewを使用しているので、是非ご利用ください!