This is a sneaky way to do it, but if you know the maximum number of buttons you're going to have, you can add it directly to your custom prototype cell on your storyboard without adding buttons programatically.
Solution (Written in Swift 4, but a general answer)
- Assuming there is a maximum of 8 answers in any question, create 8 buttons in your custom prototype cell. Add constraints as you like to make them look pretty!
- Remember to give your cell a unique identifier ("CustomCell" in my case).
- Go to File > New File > Cocoa Touch Class > Select "TableViewCell" Subclass
& give it an appropriate name (in my case
CustomCellTableViewCell.swift
). This will contain all your UI components outlets.
- Select the prototype cell in your storyboard. Navigate to the third icon from the left and select "CustomCellTableViewCell" as your class.
- Control+Drag outlets of your buttons and fields that you're going to be working with from the storyboard to your newly created
CustomCellTableViewCell.swift
. The file should now look something like this:
class CustomCellTableViewCell: UITableViewCell {
@IBOutlet weak var question: UILabel!
@IBOutlet weak var answerOne: UIButton!
@IBOutlet weak var answerTwo: UIButton!
...
...
@IBOutlet weak var answerEight: UIButton!
}
- The next few steps will be in the TableviewDataSource function
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
. Remember to cast the TableviewCell as a CustomCell:
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCellTableViewCell
- Put all the answer buttons in an array
var answerButtons = [cell.answerButtonOne, cell.answerButtonTwo..., cell.answerButtonEight]
- Now you can set the answer button text in a loop as follows:
for i in 0..<answerButtons.count {
if i < data[indexPath.row].answers.count { // if the answer exists, add it to the button
cell.answerButton[i].isHidden = false // show button if answer exists
cell.answerButton[i].setTitle(data[indexPath.row], for: .normal)
} else {
cell.answerButton[i].isHidden = true // hide that button
}
}