2017-04-06 60 views
2

我有一個單元格的表格,每個單元格顯示一個單獨的對象(鏈)。我試圖爲這些單元格中的每一個添加一個按鈕,該按鈕將該單元格的鏈作爲參數進行調用,或者至少以某種方式將其傳遞給它。我的代碼如下:RubyMotion - 傳遞參數按鈕按

def select_chain(sender) 
    unselect_old_chain 
    chain = Chain.find(sender.tag) 
    chain.selected = true 
    chain.save 
    cdq.save 
end 

def tableView(tableView, cellForRowAtIndexPath: indexPath) 
    cell = tableView.dequeueReusableCellWithIdentifier(ChainCell::ID, forIndexPath: indexPath) 
    cell.label_title.text = data_source[indexPath.row].title 
    cell.chain = data_source[indexPath.row] 
    button = UIButton.buttonWithType(UIButtonTypeCustom) 
    button.setTitle 'Go!', forState: UIControlStateNormal 
    button.tag = cell.chain.id 
    button.addTarget self, action: :select_chain, forControlEvents: UIControlEventTouchUpInside 
    button.backgroundColor= UIColor.greenColor 
    button.frame = CGRectMake(cell.frame.origin.x + 210, cell.frame.origin.y + 10, 80, 20) 
    cell.contentView.addSubview(button) 
    cell 
end 

我已經通過以下閱讀:

How to pass parameters via the selector/action?

這就提供了兩種解決方案,無論是它的工作對我來說。首先是設置一個實例變量等於變量,但是因爲我有多個單元格,我需要多個實例變量,並且會很快變得混亂。

提出另一種解決方案是使用標籤屬性,我試着在我的代碼impliment,然而這將引發錯誤:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ChainsTable select_chain]: unrecognized selector sent to instance 0x1169b9000' 

至於我,我只是用看一個整數,試圖找到鏈Chain.find(sender.tag),但是這是行不通的。

任何意見,我怎麼能得到這種方法工作或任何其他方法是非常感謝。

在此先感謝。

回答

1

我認爲你需要把它寫這樣的:

button.addTarget self, action: 'select_chain:', forControlEvents: UIControlEventTouchUpInside 

不要使用符號作爲選擇。