chronycles chronycles - 6 months ago 23
Swift Question

iOS SWIFT : Center UIButton in TableViewCell

I would like to make my custom button to center in tableView Cell, because It feels like the button somehow offset to the left (I think it's because of the frame for accessory type.
I have tried using the didselectrowatindexpath but I feel like I want to do it with UIButton. Do you have any idea how to make my button in tableviewcell center? I have tried using self.view.center but it doesn't work. here's the code:

self.buatAkunBtn = UIButton(frame: CGRectInset(self.buatAkunBtnCell.contentView.bounds, 0, 0))
self.buatAkunBtn.setTitle("Masuk", forState: UIControlState.Normal)
self.buatAkunBtn.setTitleColor(acehBusColor, forState: .Normal)
self.buatAkunBtn.addTarget(self, action: Selector("btncreateAccTapped:"), forControlEvents: .TouchUpInside)
self.buatAkunBtnCell.addSubview(self.buatAkunBtn)


Here's the image from which caused by the code above:
image offset to the left not centralised

Answer

METHOD 0:

If you absolutely want to use code. Here is how I would solve your case:

self.buatAkunBtn = UIButton(frame: CGRectInset(self.buatAkunBtnCell.contentView.frame.offsetBy(dx: 30, dy: 0), 0, 0))
self.buatAkunBtn.setTitle("Masuk", forState: UIControlState.Normal)
self.buatAkunBtn.setTitleColor(acehBusColor, forState: .Normal)
self.buatAkunBtn.addTarget(self, action: Selector("btncreateAccTapped:"), forControlEvents: .TouchUpInside)
self.buatAkunBtnCell.addSubview(self.buatAkunBtn)

Or you can use the Interface builder which would be much simpler and elegant.

METHOD 1:

1) Click on your UIButton.

2) Add constraints relative to Cell 0 to left, 0 to right.

enter image description here

3) Your UIButton is now centered.

METHOD 2 (recommended):

1) Click on your UIButton.

2) Ctrl drag from your button to your cell.

enter image description here

3) Select "center horizontally in container".

enter image description here

METHOD 3 (recommended):

1) Click on your UIButton.

2) Click on the alignment constraint icon at the bottom right.

3) Click on the checkbox: "center horizontally in container"

enter image description here

Comments