ioswatchkitwkinterfacetable

WKInterfaceTable how to identify button in each of the row?


I had for loop out 3 buttons in the table row and it will redirect to the related details when pressed.

Problem is how to identify which button users click? I have tried setAccessibilityLabel and setValue forKey but both do not work.


Solution

  • You need to use delegate in your CustomRow Class.

    In CustomRow.h file:

    @protocol CustomRowDelegate;
    
    @interface CustomRow : NSObject
    @property (weak, nonatomic) id <CustomRowDelegate> deleagte;
    
    @property (assign, nonatomic) NSInteger index;
    
    @property (weak, nonatomic) IBOutlet WKInterfaceButton *button;
    @end
    
    @protocol CustomRowDelegate <NSObject>
    
    - (void)didSelectButton:(WKInterfaceButton *)button onCellWithIndex:(NSInteger)index;
    
    @end
    

    In CustomRow.m file you need to add IBAction connected to your button in IB. Then handle this action:

    - (IBAction)buttonAction {
        [self.deleagte didSelectButton:self.button onCellWithIndex:self.index];
    }
    

    In YourInterfaceController.m class in method where you configure rows:

    - (void)configureRows {
    
        NSArray *items = @[*anyArrayWithData*];
    
        [self.tableView setNumberOfRows:items.count withRowType:@"Row"];
        NSInteger rowCount = self.tableView.numberOfRows;
    
        for (NSInteger i = 0; i < rowCount; i++) {
    
            CustomRow* row = [self.tableView rowControllerAtIndex:i];
    
            row.deleagte = self;
            row.index = i;
        }
     }
    

    Now you have just to implement your delegate method:

    - (void)didSelectButton:(WKInterfaceButton *)button onCellWithIndex:(NSInteger)index {
         NSLog(@" button pressed on row at index: %d", index);
    }