如何在 Objective-C 中从原型单元引用 parent UIViewController?
How in Objective-C to reference parent UIViewController from prototype cell?
我有一个幻灯片菜单。它是使用组件 SWRevealViewController
实现的。为了实现它,我有 1 个主要 UIViewController
(VC
) - SWRevealViewController
。我有 menu VC
并且我有 push segues
导航到不同的 menu VCs
.
对于菜单,我为每个菜单使用带有自定义 class 的原型单元格。
我的问题是我需要调用 unwind segue
去 login VC
,使用 alert view
。为此,我尝试使用常用方法 [self performSegueWithIdentifier:@"unwSegReturnToLogin" sender:self];
来自 alert view
的肯定答案(在 exit
单元格的自定义 class 内)。我在 login VC
中声明了这样的方法。我在编译期间收到错误消息:
No visible @interface for 'tvcellExitMenuItem' declares
the selector 'performSegueWithIdentifier:sender:'
我怀疑问题是 self
在我的例子中是 table cell
而不是 UIViewController
。
如果是这种情况如何参考parentVC
?
如果不对,请告诉我逻辑哪里错了。
子视图不必知道其父视图 viewController。相反,适合您需要的常见模式是 delegate 模式:为您的单元 class 定义一个委托 属性 和协议。
// your cell class header might look like this
@class MyCellClass;
@protocol MyCellDelegate
- (void)onCellSelected:(MyCellClass *)cell;
@end
@interface MyCellClass
@property (nonatomic, weak) id<MyCellDelegate> delegate;
@end
例如,如果您的 viewController 也是您的 UITableViewDatasource
,那么在 tableView:cellForRowAtIndexPath:
中,您可以将单元格的委托设置为 self
,并在中调用 segue 方法委托方法。
- (void)onCellSelected:(MyCellClass *)cell
{
// retrieve cell indexPath
NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];
// using indexPth, retrieve cell's data
// push segue with data selected
}
当然,这只是一个例子,还有其他正确的做法。
我有一个幻灯片菜单。它是使用组件 SWRevealViewController
实现的。为了实现它,我有 1 个主要 UIViewController
(VC
) - SWRevealViewController
。我有 menu VC
并且我有 push segues
导航到不同的 menu VCs
.
对于菜单,我为每个菜单使用带有自定义 class 的原型单元格。
我的问题是我需要调用 unwind segue
去 login VC
,使用 alert view
。为此,我尝试使用常用方法 [self performSegueWithIdentifier:@"unwSegReturnToLogin" sender:self];
来自 alert view
的肯定答案(在 exit
单元格的自定义 class 内)。我在 login VC
中声明了这样的方法。我在编译期间收到错误消息:
No visible @interface for 'tvcellExitMenuItem' declares
the selector 'performSegueWithIdentifier:sender:'
我怀疑问题是 self
在我的例子中是 table cell
而不是 UIViewController
。
如果是这种情况如何参考parentVC
?
如果不对,请告诉我逻辑哪里错了。
子视图不必知道其父视图 viewController。相反,适合您需要的常见模式是 delegate 模式:为您的单元 class 定义一个委托 属性 和协议。
// your cell class header might look like this
@class MyCellClass;
@protocol MyCellDelegate
- (void)onCellSelected:(MyCellClass *)cell;
@end
@interface MyCellClass
@property (nonatomic, weak) id<MyCellDelegate> delegate;
@end
例如,如果您的 viewController 也是您的 UITableViewDatasource
,那么在 tableView:cellForRowAtIndexPath:
中,您可以将单元格的委托设置为 self
,并在中调用 segue 方法委托方法。
- (void)onCellSelected:(MyCellClass *)cell
{
// retrieve cell indexPath
NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];
// using indexPth, retrieve cell's data
// push segue with data selected
}
当然,这只是一个例子,还有其他正确的做法。