2017-11-24 5 views
1

私はUITableViewCellにアクションボタンがあり、ボタンが押されたときと、ViewControllerから押されたセルの番号を検出して、ViewController.swiftでオーディオ再生リストを作成したいと考えています。スウィフト - ViewControllerからUItableViewCellのアクションボタンを検出する方法がありますか?

私はしばらくの間この問題に悩まされています。私はあなたのアドバイスを本当に申し上げます。ここにコードがあります。

ViewController.swift

import UIKit 

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

    @IBOutlet weak var tableView: UITableView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     tableView.delegate = self 
     tableView.dataSource = self 

     tableView.register(UINib(nibName: "Cell", bundle: nil), forCellReuseIdentifier: "cell") 

    } 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return 3 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! Cell 
     return cell 

    } 


} 

Cell.swift

import UIKit 

class Cell: UITableViewCell { 

    @IBOutlet weak var button: UIButton! 

    @IBAction func buttonPressed(_ sender: Any) { 

     ***[Code to send the pressed cell's number to ViewController]*** 

    } 

} 
+0

ルックの中にこれを試してみてください。 –

+0

より具体的に教えてください。ありがとうございました。 – coonie

答えて

2

あなたは古き良きデリゲートパターンのために行くことができます。これには、セルからビューコントローラを結合しないという利点があります。代理人weakに保持期間を避けることを忘れないでください。

テーブルビューからセルインデックスパスを見つけることができます。

protocol CellDelegate: class { 
    func didTap(_ cell: Cell) 
} 

class Cell: UITableViewCell { 

    weak var delegate: CellDelegate? 
    @IBAction func buttonPressed(_ sender: Any) { 
     delegate?.didTap(self) 
    } 
} 

class ViewController: UIViewController, CellDelegate { 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = ... 
     cell.delegate = self 
     return cell 
    } 

    func didTap(_ cell: Cell) { 
     let indexPath = self.tableView.indexPath(for: cell) 
     // do something with the index path 
    } 
} 
+2

あなたの 'didTap'の実装は変です。次のようにします: 'let indexPath = self.tableView.indexPath(for:cell)'。目に見える細胞をスキャンする必要はありません。 – rmaddy

-1

(私はあなたのインデックスパスの平均細胞数で仮定している)デリゲートのためのあなたのViewConroller

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! Cell 

     //add tag to cell button to that of cell index 
     cell.button.tag = indexPath.row 

     //Observer for button click event inside cell 
     cell.button.addTarget(self, action: #selector(pressButton(_:)), for: .touchUpInside) 

     return cell 

    } 

//Mark: Button Action 

@objc func pressButton(_ button: UIButton) { 
    print("Button with tag: \(button.tag) clicked in cell!") 
} 
関連する問題