4

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.

return true
  • 7,839
  • 2
  • 19
  • 35
Ngo Yen Sern
  • 105
  • 4

3 Answers3

6

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);
}
Hopreeeenjust
  • 257
  • 4
  • 5
  • `[ContactController didSelectButton:onCellWithIndex:]: unrecognized selector sent to instance ` Why does my code has this error? I follow your code exactly? does my button linking has problem? – Ngo Yen Sern Apr 01 '16 at 09:39
  • _@Ngo Yen Sern_, didSelectButton:onCellWithIndex: should be called not from controller class, but from *Cell* class. And your controller should be a delegate of the cell – Hopreeeenjust Apr 01 '16 at 10:22
3

If a button is pressed, WatchKit will call the following method:

- (void)table:(WKInterfaceTable *)table didSelectRowAtIndex:(NSInteger)rowIndex

Use the rowIndex parameter to decide which action should be done then.

return true
  • 7,839
  • 2
  • 19
  • 35
fredpi
  • 8,414
  • 5
  • 41
  • 61
0

try to put (sender: UIButton) in your IBAction like this:

@IBAction func buttonPressed(sender: UIButton)

AziCode
  • 2,510
  • 6
  • 27
  • 53