Nathern Nathern - 3 months ago 7
Swift Question

swift dynamic list with multiple labels per row that can be selected, highlighted and capture the value

I’ve developed a survey that allows users to enter five questions with a response selection from 1 to 5. My current version has five labels for the questions and five buttons for the response values. The labels and number values are pulled from a database. When the form is submitted I pass the question and selected response value back to the database. I’m trying to figure out how to create a dynamic survey that is not limited on the number of questions.

In testing I did develop a survey using a table view and custom cell. In the cell I had five labels, one for the question and the rest were response selection labels. The problem I had was trying to select an individual label for each question and highlighting the selected response.

Is it possible to create a dynamic list with multiple labels per row that can be selected, highlighted and capture the value? I’m new to XCODE and swift so I may be going about this the wrong way.

My current survey image

Answer

If you change your labels to buttons, you can capture the value when the button is pressed and store it in an array corresponding to its row number.

var answers: [String] = []

@IBAction func ratingButtonPressed(sender: AnyObject) {
    let button = sender as! UIButton // This is the rating button that was pressed inside the cell
    let currentCell = button.superview!.superview!.superview! as! MatchupCell // This gets the cell that has that pressed button
    let indexPath = tableView.indexPathForCell(currentCell)
    currentRow = (indexPath?.row)! // This gets the row of the cell

    answers[currentRow] = button.titleLabel!.text! // Store the pressed value in the array at the index that matches the row number
}
Comments