Pass a method from my custom cells class to the main class

前端 未结 6 1731
余生分开走
余生分开走 2020-12-22 06:04

I have a custom cell. In it is a UITextField linked to customCell.m. I\'m trying to pass the text from the textField to mainVC.m

6条回答
  •  别那么骄傲
    2020-12-22 06:54

    What you need to do is:

    1. Define a protocol
    2. Add a property of this protocol for your CustomCell
    3. Implement the protocol in your MainVC

    1. Define a protocol

    We normally put the definition of the protocol in the header file (in this case CustomCell.h).

     // define the protocol for the delegate
     @protocol CustomCellDelegate 
     // define protocol functions that can be used in any class using this delegate
     -(void)customCell:(CustomCell *)customCell passText:(NSString *)text;
     @end
    

    2. Add a property of this protocol for your CustomCell

    And add this to your CustomCell between @interface CustomCell and @end.

    @property (nonatomic, weak) id delegate; 
    

    3. Implement the protocol in your MainVC

    In your MainVC, implement the delegate function as the following.

    @interface MainCV
    @end
    
    @implementation MainVC 
    -(void)customCell:(CustomCell *)customCell passText:(NSString *)text
    {
         // Do whatever you want with text here
    }
    @end
    

    The following shows how you use the protocol above.

    1. Set the delegate when create CustomCell in your MainCV. Something like the following,

      CustomCell *cell = ... allocation and initialization
      cell.delegate = self; // self is mainVC
      
    2. Whenever you need to pass the data NSString in your customCell, call the following:

      [self.delegate customCell:self passText:self.myTextField.text]; // self is customCell
      

提交回复
热议问题