Nick Pitoniak
Nick Pitoniak

Reputation: 97

How to programmatically add a button to UITableView row?

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
}

Upvotes: 1

Views: 2514

Answers (1)

joern
joern

Reputation: 27620

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.

Upvotes: 3

Related Questions