flysaiah flysaiah - 1 month ago 21
Swift Question

Swift make percentage of width programmatically

I am programmatically creating multiple buttons in Swift for a UITableViewCell, and would like to set their widths to be a certain percentage width of the UITableViewCell so that they use up all of the space. Right now I am creating the buttons in a for loop (I want to be able to create a variable amount of buttons) and am using

button.buttonWidth = self.contentView.frame.width / numberOfButtons


where button is a UIButton and self is a UITableViewCell and numberOfButtons is obviously the number of buttons. I have also tried:

button.buttonWidth = self.frame.size.width / numberOfButtons


and every combination of using/not using .size and using/not using contentView. These don't seem to work, however, as the buttons are too big. Anyone know how to accomplish this?

NOTE: I CAN'T use Autolayout in the storyboard, as I'm creating a variable number of buttons.

Answer

Maybe because you're doing this before the cell layouts its subviews and it's size is the same as size set in Any-Any size class 600 * 600.

Try doing adding your buttons in layoutSubviews method, like this:

override func layoutSubviews() {
    super.layoutSubviews()
    self.layoutIfNeeded()

    // add your buttons here

}