将方法从我的自定义单元格类传递给主类 [英] Pass a method from my custom cells class to the main class

查看:87
本文介绍了将方法从我的自定义单元格类传递给主类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义单元格。它是 UITextField 链接到 customCell.m 。我正在尝试将文本从 textField 传递到 mainVC.m

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.

我在 customCell.m 中有一个公共方法:

I have a public method in customCell.m:

- (NSString *)PassText{
   return self.myTextField.text;
}

如何将该方法传递给我的 mainVC.m ?

How can I pass that method to a string in my mainVC.m?

推荐答案

您需要做的是:


  1. 定义协议

  2. 为您的 CustomCell
  3. $添加此协议的属性b $ b
  4. MainVC中实施协议

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

1。定义协议

我们通常将协议的定义放在头文件中(在本例中为 CustomCell.h )。

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。为您的 CustomCell

2. Add a property of this protocol for your CustomCell

添加此协议的属性并将其添加到您的 CustomCell 介于 @interface CustomCell @end 之间。

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

@property (nonatomic, weak) id<CustomCellDelegate> delegate; 

3。在 MainVC中实施协议

3. Implement the protocol in your MainVC

MainVC ,实现委托函数如下。

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

@interface MainCV<CustomCellDelegate>
@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. 在<$ c $中创建 CustomCell 时设置委托C> MainCV 。如下所示,

  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


  • 每当您需要在customCell中传递数据NSString时,请致电以下内容:

  • 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
    


  • 这篇关于将方法从我的自定义单元格类传递给主类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆