简体   繁体   中英

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.

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);
}

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.

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

@IBAction func buttonPressed(sender: UIButton)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM