【发布时间】:2017-04-06 15:02:59
【问题描述】:
我有一个单元格表,每个单元格显示一个单独的对象(链)。我正在尝试为每个单元格添加一个按钮,该按钮以该单元格的链作为参数调用一个动作,或者至少以某种方式将其传递给它。我的代码如下:
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?
这提供了两种解决方案,但都不适合我。第一个是将实例变量设置为等于该变量,但是由于我有多个单元格,我需要多个实例变量,这会很快变得混乱。
提出的另一个解决方案是使用 tag 属性,我试图在我的代码中隐含该属性,但这会引发错误:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ChainsTable select_chain]: unrecognized selector sent to instance 0x1169b9000'
据我所知,我只是使用整数来尝试使用 Chain.find(sender.tag) 找到链,但这不起作用。
非常感谢任何有关我如何使此方法或任何其他方法起作用的建议。
提前致谢。
【问题讨论】:
标签: ruby-on-rails ruby rubymotion