Search code examples
iosdelegatescustom-cell

Run Delegate Method in viewcontroller directly from Custom Cell


I have setup a delegate method on Custom cell. let's say,

@protocol CheckDelegate <NSObject>
@required
- (void)checkForUpdate;
@end
@property (nonatomic, weak) id<CheckDelegate> delegateForChecker;

-- I will call above function somewhere in my cell ---

and I want to listen for any change in Custom Cell at Viewcontroller. How can I implement this using the delegate in Viewcontroller without using tableviewcontroller.

In ViewController I though about doing,

-(void) viewDidLoad{
  CustomCell * cll = [[Customcell alloc]init]
  cll.delegateForChecker = self;
}

-(void) checkDelegate{
  NSLog(@"Something changed");
}

P.S. I do not want use NSNotification


Solution

  • I came up with different approach to pass the data from cell to another viewcontroller (not the tableviewcontroller where the cell is instantiated) using block. This may help someone who may find themselves stuck with this issue. In custom cell, I created a block property called that would pass the property to the tableviewcontroller where the cell is instantied.

    @property  (copy, nonatomic) void (^didTouchButtonOnCell) (BOOL selectedButton);
    

    In button touched in customCell I set the boolean property with Boolean Value.

     self.didTouchButtOnCell(YES/NO);
    

    In the tableViewcontroller I created another block that would pass data to the viewcontroller where I intended to pass the Boolean value. In the TableViewController,

     @property (copy, nonatomic) void (^passBooleanToViewController) (BOOL selectionFromButton)
    

    In cellForRowAtIndexPath in TableViewController, I get the boolean property and pass it to ^passBooleanToViewController.

        cell.didTouchButtonCell = ^(BOOL selection)
       {
          passBooleanToViewController(selection)
        }
    

    Finally, in ViewController I again get the Block property of TableViewcontroller that contained the Boolean value that was passed over to TableViewController from CustomCell

    Viewcontroller.passBooleanToViewController = ^(Bool sel){
        NSLog(@"%I here is the boolean value",sel);
    }
    

    ** This is one of the ways I was able to fix the issue of passing value from custom cell to viewcontroller. It would be great if some other approaches can be shared too.