2017-04-26 44 views
0

我能夠生成UITableViewUITableViewCell但是我的操作無法正常工作。我的使用情況類同this video遞歸UITableViewCell按鈕操作

我用this問題作爲參考,是uncesscessful

我缺少什麼?快速3相關的東西?

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。在操作調用回調

class CustomCell: UITableViewCell { 

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

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

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

cellForRow分配一個封閉的回調,指數路徑被捕獲。

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

控制檯沒有響應,它看起來像你的「#選擇器(self.logAction)」可能是錯誤的。它應該看起來像「logAction(發件人:)」。 – naturaln0va

0

是啊,所以我剛剛刪除的視圖控制器和重拍,現在可_(ツ)_ /¯