Search code examples
iosswifttableviewwatchkitwatchos-2

insertRowAtIndexes watchKit Swift


I have a struct

struct Question {
    var title: [String]
    var additionalInfo: String?
    var answers: [String]
}

and a variable to which i add the data

var questions = [
    Question(title: ["What is the color of?", "additional color information"], additionalInfo: nil, answers: [
        "Blue",
        "Gray"
        ])
]

This data loads up in a tableView on AppleWatch. Two row types are separated - TitleRowType (for titles array) and AnswersRowType (for answers array).

When i insert values into struct's array - i want to the rows in the tableView be inserted with animation.

I know that there's a insertRowAtIndexes function, but i cannot wrap my head around it. The example provided in Apple's documentation doesn't work for me. That's what i came up with:

    let indexSet = NSIndexSet(index: Int) // Int is passed via the function
    tableView.insertRowsAtIndexes(indexSet, withRowType: "TitleRowType")

but when i run it - the table doesn't update. Looking forward to your advices.


Solution

  • You have to do 3 steps:

    1. Add the new data to your array
    2. Insert a row into the table
    3. Populate the row with the new data

    Here is a simple example:

    class InterfaceController: WKInterfaceController {
    
        @IBOutlet var table: WKInterfaceTable!
        var items = ["row1", "row2", "row3"]
    
        override func awakeWithContext(context: AnyObject?) {
            super.awakeWithContext(context)
            loadTable()
        }
    
        func loadTable() {
            table.setNumberOfRows(items.count, withRowType: "tableRow")
            var rowIndex = 0
            for item in items {
                if let row = table.rowControllerAtIndex(rowIndex) as? TableRowController {
                    row.label.setText(item)
                }
                rowIndex++
            }
        }
    
        @IBAction func insertRow() {
            items.append("row4")
            let newIndex = items.count
            table.insertRowsAtIndexes(NSIndexSet(index: newIndex), withRowType: "tableRow")
            if let row = table.rowControllerAtIndex(newIndex) as? TableRowController {
                row.label.setText(items[newIndex])
            }
        }
    }
    

    TableRowController is a NSObject subclass that has one WKInterfaceLabel outlet to display the number of the row.

    I used a button to trigger insertRow()