Billd Billd - 1 year ago 107
Swift Question

Adding UIButton to the center of a UITableViewCell using Swift

The following code only shows button in the last row of the table. Any thoughts on why?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

var cell:UITableViewCell = self.myTable.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

let button : UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
button.frame = CGRectMake(40, 60, 100, 24) =
button.backgroundColor = UIColor.redColor()
button.addTarget(self, action: "buttonClicked:", forControlEvents:
button.setTitle("Click Me !", forState: UIControlState.Normal)
return cell

Answer Source

Instead of =


let cellHeight: CGFloat = 44.0 = CGPoint(x: view.bounds.width / 2.0, y: cellHeight / 2.0)

This assumes that your tableView is full width and your cellHeight is 44.0. You can't get the actual height from the cell itself just yet. If you want the actual height you'd have to get it from the tableView:willDisplayCell:forRowAtIndexPath: method or do something else.

Also instead of using self.myTable you should use the tableView variable in the method itself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download