2016-07-25 14 views
0

私は既にindexPathForRowAtPointソリューションを試しましたが、最初はうまくいきましたが、今は何が壊れたのか分かりません。誰かが私が作ったかもしれないいくつかのよくある間違いが何であるかについてのアドバイスを持っていますか?ありがとう。Swiftでは、ボタンを押したセルの行を取得するにはどうすればよいですか?

let pointInTable = sender.convertPoint(sender.bounds.origin, toView: self.tableView) 
    let index = self.tableView.indexPathForRowAtPoint(pointInTable)?.row 
    let prod_id = list[index].getProdID() 
+1

これを処理するには、indexPathForRowAtPointを使用するのが良い方法です。コードを投稿すると、デバッグに役立ちます。 –

+1

[tableviewで押されたuibuttonの検出:Swiftのベストプラクティス]の複製が可能です(http://stackoverflow.com/questions/27429652/detecting-uibutton-pressed-in-tableview-swift-best-practices) –

+0

私はコード...また、私は、タグを設定し、別の目的のために使用されるので、sender.tagオプションは実行可能ではありません。 – OOProg

答えて

0

私は、データソース(ノートで

import UIKit 

class ButtonCell: UITableViewCell { 

    @IBOutlet weak var button: UIButton! { 
     didSet{ 
      button.addTarget(self, action: #selector(ButtonCell.buttonTapped(_:)), forControlEvents: .TouchUpInside) 
     } 
    } 

    var buttonWasTapped: ((cell: ButtonCell) -> Void)? 

    override func setSelected(selected: Bool, animated: Bool) { 
     super.setSelected(selected, animated: animated) 
    } 

    func buttonTapped(sender:UIButton) { 
     buttonWasTapped?(cell: self) 
    } 
} 

Now]ボタンによってトリガクロージャーコールバックを持っているでしょうカスタムセル、作成します。より良いここにビューコントローラに実装は、別々のだろうデータソースオブジェクト)セルを識別するためにコールバックを設定し、インデックスパスを取得します。

import UIKit 

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

    @IBOutlet weak var tableView: UITableView! 
    func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 1 
    } 

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! ButtonCell 
     cell.buttonWasTapped = { 
      cell in 
      let idxPath = tableView.indexPathForCell(cell) 
      let alert = UIAlertController(title: "tapped", message: "cell at indexpath: \(idxPath)", preferredStyle: .Alert) 
      alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) 
      self.presentViewController(alert, animated: true, completion: nil) 
     } 
     return cell 
    } 
} 
関連する問題