LoginSignup
1
2

More than 3 years have passed since last update.

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

Posted at

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
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2