1

I am attempting to add a button to a UITableView row that will interact with a MySQL database via a NSURL session. I have successfully pragmatically added buttons to a blank view controller, however it will not work when duplicated with a UITableView cell. No error is given
Code:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
    cell.textLabel?.text = self.textArray.objectAtIndex(indexPath.row) as? String

    let button = UIButton(type: UIButtonType.System)
    button.frame = CGRectMake(100, 100, 120, 50)
    button.backgroundColor = UIColor.greenColor()
    button.setTitle("Test Button", forState: UIControlState.Normal)
    button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)

    cell.addSubview(button)


    return cell
}
2
  • Can you specify what is not working. Does the button not appear? Commented Nov 14, 2015 at 23:46
  • Yes. The button does not appear. Commented Nov 15, 2015 at 2:16

1 Answer 1

3

There are two issues with your approach:

  1. When you add subviews to a UITableViewCell you are supposed to add them to the cell's contentView and not directly to the cell.

  2. Cell's are being reused. When the user scrolls and the cell is not visible anymore it gets added to the table view's cell queue. Then when the table needs to display a new cell it dequeues an old cell from that queue and shows it again. Because the cell already has been displayed earlier it already has a button. But you are adding another button to the cell. Even if it already has a button. So before adding a button you should check if the cell already has a button. However a better approach would be to create your own subclass of UITableViewCell and add the button in the cell's initializer.

And just double checking: Are you sure your cell is heigh enough to display the button? The frame you set on the button needs a cell with at least a height of 150.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.