
基本的にUI部品はOutlet接続してViewControllerに繋いで管理するのが一般的ですが、tableViewCellの上に乗っかったUI部品はOutlet接続できない場合があります。
そんな時に便利なのがUI部品をタグで管理するやり方です。
やり方
まず、タグ付けしたいUI部品を選択してAttributs Inspecterを開けます。
そして画面右下の【View】の【Tag】に任意の数字を入れます。この部品はその数字のTagで管理されることになります。
画像で言うと、「ユーザーネーム」はTag「2」で管理されます。
fa-chevron-circle-rightコード
該当コードのみ抜粋
1 2 3 4 5 6 7 8 9 10 |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let profileImageView = cell.viewWithTag(1) as! UIImageView let userNameLabel = cell.viewWithTag(2) as! UILabel let odaiImageView = cell.viewWithTag(3) as! UIImageView let commentTextView = cell.viewWithTag(4) as! UITextView } |
私の場合はtableViewCellの上に乗っかったUI部品にタグをつけたので、cellForRowAt
の中で定義しました。
【タグづけしたいUI部品】 = cell.viewWithTag(数字) as! UIImageView
これで管理ができるようになります。