iosswiftwatchkitwkinterfacetable

WKInterfaceTable, WKInterfaceButton and action methods


I'm experimenting with WatchKit and I'm trying to accomplish something that may be obvious but I can't seem to figure out how.

I have a single watch interface that contains a table with several rows of the same row controller, each containing two buttons. The action methods for the buttons are contained in the appropriate row controller class. The background image of the button changes each time it is tapped. That all works. However, I also need to call a function in the interface controller and change some variables that exist in the interface controller, each time the button is tapped.

Is this possible? I also understand that I can't call didSelectRowAtIndex at the same time as my button action.

Thanks!


Solution

  • You will need to wire your InterfaceController to your buttons and then call the appropriate method. It is best to decouple it via a delegate or using a selector, but you can just past your interface controller if needed.

    This assumes you wired your WKInterfaceTable object to the property table in your interface controller.

    //In your interface controller
    - (void)loadTableData
    {
        NSInteger numRows = <CALC_NUM_ROWS>;
    
        [self.table setNumberOfRows:num withRowType:@"<MY_ROW_TYPE>"];
    
        for (int i = 0; i < num; i++)
        {
            MyRowController *row = [self.table rowControllerAtIndex:i];
    
            //Here is where you want to wire your interface controller to your row
            //You will need to add this method to your row class
            [row addSelectionTarget:self action:@selector(myMethodToCall)];
    
        }
    }
    
    - (void) myMethodToCall
    { 
       //Do something in your interface controller when a button is selection
    }
    
    
    //Now in your MyRowController
    -(void)addSelectionTarget:(id)target action:(SEL)action
    { 
        //You will need to add properties for these.
        self.selectionTarget = target;
        self.selectionAction = action;
    }
    
    //Call this when you want to call back to your interface controller
    - (void)fireSelectionAction
    {
        [self.selectionTarget performSelector:self.selectionAction];
    
        //Or to do it without warnings on ARC
        IMP imp = [self.selectionTarget methodForSelector:self.selectionAction];
        void (*func)(id, SEL) = (void *)imp;
        func(self.selectionTarget, self.selectionAction);
    
    }