1
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

UITableViwCell内のボタンからindexPathの取得方法

tableViewCell.xib でcellをカスタムした際にbutton のindexの取得が必要になり調べました。
私的備忘録として。

tableViewCellにてindexPathを定義

TableViewCell.swift
import UIKit

class TableViewCell: UITableViewCell {

    @IBOutlet weak var button: UIButton!
      var indexPath = IndexPath()

    @IBAction func button(_ sender: Any){
      print(indexPath.row)
}

cellForRowAt内でindexをcellわたす

ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self

        tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "tableViewCell")
}

extension ViewController: UITableViewDelegate, UITableViewDataSource{

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as! TableViewCell
        cell.indexPath = indexPath

        return cell
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
1
Help us understand the problem. What are the problem?