ruby-on-railsrubyrubymotion

RubyMotion - passing a parameter on button press


I have a table of cells, each displaying a separate object (Chain). I'm trying to add a button to each of these cells, which calls an action with that cell's chain as an argument, or at least passes it to it somehow. My code is as follows:

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

I've read through the following:

How to pass parameters via the selector/action?

That provides two solutions, neither of which work for me. The first is setting an instance variable to equal the variable, however as I have multiple cells I would need multiple instance variables and that would get messy quickly.

The other solution presented was to use the tag attribute, which I've tried to impliment in my code, however this throws the error:

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

As far as I can see I'm simply using an integer to try and find the Chain with Chain.find(sender.tag), however this is not working.

Any advice on how I can either get this method working or any other approaches is greatly appreciated.

Thanks in advance.


Solution

  • I think you need to write it like this:

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

    Do not use a symbol as selector.