Watchkit: table with two templates in dynamic rows

3.1k views Asked by At

How to instantiate two different templates of dynamic row in WKInterfaceTable? For only one template I use functions

 [self.stocksTable setNumberOfRows: self.stocksData.count withRowType:@"TableRow"];
 TableRow *row = [self.stocksTable rowControllerAtIndex:i];

Question: How to have 2 types of row?

3

There are 3 answers

1
Dave DeLong On BEST ANSWER

You want -[WKInterfaceTable setRowTypes:]:

[self.myTable setRowTypes:@[@"RowType1", @"RowType2"]];
MyRowType1Controller *row1 = [self.myTable rowControllerAtIndex:0];
MyRowType2Controller *row2 = [self.myTable rowControllerAtIndex:1];
0
coco On

Building on @dave-delong's (correct!) answer, most tables will have a mix of row types, and the array must reflect that. For example, a table with a header, 4 rows of info, and a footer, would require an array looking something like this:

NSArray *rowTypes = @[@"headerRowType", @"infoRowType", @"infoRowType", @"infoRowType", @"infoRowType", @"footerRowType"];
[self.myTable setRowTypes:rowTypes];
0
David On

Swift solution, for case with dynamic cell count:

    let notificationRowTypes = Array(repeating: "notificationRow", count: watchNotifications.count)
    let notificationDateRowTypes = Array(repeating: "notificationDateRow", count: watchNotifications.count)
    let rowTypes = mergeArrays(notificationDateRowTypes, notificationRowTypes)
    noficationsTable.setRowTypes(rowTypes)
    updateTableRowsContent()


func mergeArrays<T>(_ arrays:[T] ...) -> [T] {
    return (0..<arrays.map{$0.count}.max()!)
        .flatMap{i in arrays.filter{i<$0.count}.map{$0[i]} }
}

func updateTableRowsContent() {
    let numberOfRows = noficationsTable.numberOfRows
    for index in 0..<numberOfRows {
        switch index % 2 == 0 {
        case true:
            guard let controller = noficationsTable.rowController(at: index) as? NotificationDateRowController else { continue }
            controller.notification = watchNotifications[index / 2]
        case false:
            guard let controller = noficationsTable.rowController(at: index) as? NotificationRowController else { continue }
            controller.notification = watchNotifications[index / 2]
        }
    }
}