2017-04-26 18 views
0

UITableViewUITableViewCellを生成することはできますが、私の動作は正しく動作していません。私のユースケースは、私が参考にthis質問を使用していたと私は何をしないのです再帰的UITableViewCellボタンアクション

uncesscessfulた this video

に似ているのですか?何かが関連して速くなる?

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

    @IBOutlet weak var tableView: UITableView! 

    var categories = ["foo", "bar"] 

    func logAction(sender: UIButton!){ 
     print("HIT BUTTON YO") 
    } 

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return self.categories.count 
    } 

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {  
     let cell:CustomCell = tableView.dequeueReusableCell(withIdentifier: "categories", for: indexPath) as! CustomCell 
     cell.label.text = categories[indexPath.row] 
     let button = cell.button 
     button?.tag = indexPath.row 
     button?.addTarget(self, action: #selector(self.logAction), for: .touchUpInside) 
     return(cell) 
    } 
} 


class CustomCell: UITableViewCell { 

    @IBOutlet weak var button: UIButton! 
    @IBOutlet weak var label: UILabel! 


    override func awakeFromNib() { 
     super.awakeFromNib() 
    } 

    override func setSelected(_ selected: Bool, animated: Bool) { 
     super.setSelected(selected, animated: animated) 
     //Configure view for selected state 
    } 
} 
+0

クラッシュログが何を言うのでしょうか? –

+0

それはまったくクラッシュしません....私のテーブル上のボタンをクリックすると、何も起こらない.... 'tableView(_ tableView:UITableView、cellForRowAt indexPath:IndexPath)'を試してみた –

答えて

2

カスタムセルでボタン操作を処理する方法がよりスマートになりました。

カスタムセルでは、パラメータ/戻り値なしでボタンに接続されたIBActionのコールバッククロージャを作成します。アクションでインデックスパスが捕捉され、コールバックにクロージャを割り当てるcellForRow

class CustomCell: UITableViewCell { 

    @IBOutlet weak var button: UIButton! 
    @IBOutlet weak var label: UILabel! 

    var callback : (()->())? 

    @IBAction func logAction(_ sender : UIButton) { 
     callback?() 
    } 
} 

コールバックを呼び出します。

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "categories", for: indexPath) as! CustomCell 
    cell.label.text = categories[indexPath.row] 
    cell.callback = { 
     print("Button pressed", indexPath) 
    } 
    return cell 
} 

注:returnは機能ではありません(かっこはありません)。

+0

それはきれいに見えますが –

+0

カスタムセルのクラスがInterface Builderで 'CustomCell'に設定されていますか? – vadian

+0

はい、そうです。それ以外に何ができるかわからない –

0

セルのボタンに直接アクセスしてみてください。代わりに

let button = cell.button 
button?.tag = indexPath.row 
button?.addTarget(self, action: #selector(self.logAction), for: .touchUpInside) 

ボタンのプロパティを直接設定します。

cell.button.tag = indexPath.row 
cell.button.addTarget(self, action: #selector(self.logAction), for: .touchUpInside) 
+0

コンソールからの応答がありません。 –

+0

"#selector(self.logAction)"が間違っている可能性があります。 「logAction(送信者:)」のように表示されます。 – naturaln0va

0

いやいかなる場合ので、私はちょうど_今ビューコントローラを削除してリメイクし、それが動作します(ツ)_ /¯