[英]Reference view controller from custom UITableViewCell class
我有一个名为MAGradeCell
的类,它是一个自定义UITableViewCell
类。 之前,我有类和我是从视图控制器(内建立细胞MAController
),我只是configureHeaderCell
倒是在self
(从而解决是的viewController。
现在,我已经为UITableViewCell
了一个自定义类,现在我无法使用self
引用viewController了。 这是否意味着我应该alloc
和init
一个新的viewController? 还是我要做一些super
或导入viewController并获取一些接口属性或其他内容?
尝试这个,
在MAGradeCell.h
typedef void (^yourCallBack)(MAGradeCell *cell); //You may or may not use cell as parameter according to the need
将其创建为属性
@property (readwrite, copy) yourCallBack callBack;
在MAGradeCell.m
- (void)someAction {
if (self.callBack != nil) {
self.callBack(self);
}
}
单元内配置方法
MAGradeCell *cell = ....
.....
cell.callBack = ^(MAGradeCell *gradeCell) {
//Do the stuff
};
首先,您能否阐明您如何从UITableViewCell访问viewController? 您的自定义单元格应该继承UITableViewCell可用的所有内容,但是UITableViewCell并没有将视图控制器作为其属性之一,因此我有点困惑您以前的使用方式,因为它无法应用于子类。
如果您希望单元格从viewController中检索某些信息,或者将其通知某些内容,或者将消息传递给它,则可以使用以下委托:
您可以在MAGradeCell.h中为单元创建委托:
@protocol MAGradeCellDelegate <NSObject>
-(void)specialMethodWithCell:(UITableViewCell*)cell;
@end
@interface MAGradeCell:UITableViewCell
//...
@property (nonatomic, weak) id<MAGradeCellDelegate>delegate;
//...
@end
然后在您的MAGradeCel.m中执行以下操作:
if([self.delegate respondsToSelector:@selector(specialMethodWithCell:)])
{
[self.delegate specialMethodWithCell:self];
}
然后,在视图控制器的.h文件中,确保您声明要实现此协议,并在创建单元格时将其委托分配为self。
在本教程中,对委派进行了一些描述(以及其他一些非常有用的设计模式): http : //www.raywenderlich.com/46988/ios-design-patterns
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.