Search code examples
rubymotion

Data only populates in last UITextField in UITableViewCell


I have a tableview that has names and text fields in the accessoryView position. With the following UITableViewDelegate method, I am calling onEdit and it calls a UIPickerView. The problem is, if I have more then 1 cell, it only populates the data in the last uitextfield no matter which textfield I click on. How do I allow data to go into the text field I am editing?

 def tableView(tableView, cellForRowAtIndexPath: indexPath)
@reuseIdentifier ||= "CELL_IDENTIFIER"

cell = tableView.dequeueReusableCellWithIdentifier(@reuseIdentifier) || begin     
   UITableViewCell.alloc.initWithStyle(UITableViewCellStyleDefault, reuseIdentifier:@reuseIdentifier)
end



  picker = UIPickerView.alloc.initWithFrame([[0, self.view.frame.size.height / 2 + 50], [self.view.frame.size.width, self.view.frame.size.height]])
  picker.delegate = self
  picker.showsSelectionIndicator = true

  @picker_field = UITextField.alloc.initWithFrame([[200,20],[150,40]])
  @picker_field.placeholder = "Choose Location.."
  @picker_field.delegate = self
  @picker_field.inputView = picker


  cell.textLabel.text = @list[indexPath.row]
  cell.accessoryView = @picker_field
  cell.selectedBackgroundView.backgroundColor = UIColor.redColor




  #cell.selectionStyle = UITableViewCellSelectionStyleNone

cell
end

  def pickerView(pickerView, numberOfRowsInComponent: component)
@choices_count
  end

  def  pickerView(pickerView, titleForRow: row, forComponent: component)
@choices[row]
  end

  def pickerView(pickerView, didSelectRow: row, inComponent: component)
    @picker_field.text = @choices[row]
    @picker_field.resignFirstResponder

  end

Solution

  • The solution came from putting more focus on the @picker_field becoming the firstResponder. Once I put an if statement stating the firstResponder it populates everytime.

      def pickerView(pickerView, didSelectRow: row, inComponent: component)
        if @picker_field = firstResponder
          @picker_field.text = @choices[row]
          @picker_field.resignFirstResponder
        end
       end