1
votes

I am making a multiple choice test, and I don't know how to get the answers the user selected so I can grade the test.

I have a view controller (connected to a navigation controller) in the storyboard that has a table view, and I use a xib file for my custom cell.

These are my two classes:

ViewController class - holds a table view - is my data source - loads data into my xib table view cell - navigation bar has a button called "Grade"

Table view cell class - has a label outlet that displays a question - has three button outlets that display answer choices - has an action that changes the background color of the button when tapped

Loading the questions and answer choices data into the xib cell works fine.

When the user clicks the "Grade" button, I want to store the titleLabel text of all the buttons the user tapped in an array, but I don't know how to do this.

1
You could create a delegation from the cell back to the view controller so that the button taps in the cell can update the model held by the view controller.Paulw11

1 Answers

1
votes

The typical pattern for this sort of thing would be to define a delegate protocol that would receive events from your UITableViewCells, such as the tap of a button. The delegate can send along which cell and which button in which cell was tapped, so your TableView or ViewController can update its view model on which of the buttons have been tapped view-wide.

class AnswerCellView: UITableViewCell {
    // ...

    weak var delegate: AnswerCellViewDelegate?

    // The methods here linked to your outlets should call the answerCellClicked on the delegate

    // ...
}

protocol AnswerCellViewDelegate {
    func answerCellClicked(answerCell: AnswerCellView, answerButton: UIButton)
}

// ...

class AnswerCellTableView: UITableViewDataSource, AnswerCellViewDelegate {
    // ...

    func answerCellClicked(answerCell: AnswerCellView, answer: UIButton) {
        // do the work to keep track of which buttons have been clicked
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var answerCell: AnswerCellView
        // construct your AnswerCellView, setting the delegate property on your cell to self
        // ...
        answerCell.delegate = self
        // ...
    }

    // ...
}