所以我有这个 BaseCell
类也有这个 BaseCellViewModel
.当然,除此之外还有一些FancyViewController
与 FancyViewModel
.这里的情况是 BaseCell
有UIButton
在它上面触发这个 IBAction
方法 - 这很好而且很酷,因为我可以在那里做任何我想做的事,但是......我不知道我应该如何让知道 FacyViewController
关于在 BaseCell
上发生了一些操作的事实.
我可以RACObserve
FancViewModel
的特性因为它有NSArray
这些单元格 View 模型,但如何监控实际操作并通知单元格上触发的确切操作?
我首先想到的是委派或通知,但既然我们的项目中有 RAC,那么不使用它就太愚蠢了,对吧?
[编辑] 到目前为止我做了什么......
所以,事实证明你可以使用 RACCommand
实际处理特定按钮上的 UI 事件。在这种情况下,我添加了:
@property (strong, nonatomic) RACCommand *showAction;
到我的BaseCellViewModel
简单的实现,如:
- (RACCommand *)showAction {
return [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
NSLog(@"TEST");
return [[RACSignal empty] logAll];
}];
}
按照这种模式,我必须在我的 BaseCell
中做一些事情结果非常简单,我最后添加了:
- (void)configureWithViewModel:(JDLBasePostCellViewModel *)viewModel {
self.viewModel = viewModel;
self.actionButton.rac_command = self.viewModel.showAction;
}
而且... 它有效! 但是...
我需要出示 UIActionSheet
每当这种情况发生时,只有在我需要当前 parentViewController
时才会显示由于我没有在任何地方传递此类信息,所以我现在不知道该怎么做。
FancyViewModel
拥有私有(private)@property (nonatomic, strong) NSMutableArray <BaseCellViewModel *> *cellViewModels;
, 但我怎样才能在 FancyViewController
上注册一些东西呢?实际监听执行RACCommand
在 BaseCellViewModel
?
最佳答案
单元格可以通过几种方式与 View Controller 通信。一个常见的方法是通过委托(delegate)。让单元格声明一个公共(public)代表,例如:
// BaseCell.h
@protocol BaseCellDelegate;
@interface BaseCell : UITableViewCell
@property(nonatomic, weak) id<BaseCellDelegate> delegate;
// ...
@end
@protocol BaseCellDelegate <NSObject>
- (void)baseCell:(BaseCell *)cell didReceiveAction:(NSString *)actionName;
@end
当按钮被按下时,想出你想告诉委托(delegate)人什么,然后告诉它:
// BaseCell.m
- (IBAction)buttonWasPressed:(id)sender {
self.delegate baseCell:self didReceiveAction:@"someAction";
}
然后,在 View Controller 中,声明您遵守协议(protocol):
// FancyViewController.m
@interface FancyViewController () <BaseCellDelegate>
在 cellForRowAtIndexPath
中,设置单元格的委托(delegate):
// dequeue, etc
cell.delegate = self;
你现在需要在 vc 中实现它:
- (void)baseCell:(BaseCell *)cell didReceiveAction:(NSString *)actionName {
// the cell got an action, but at what index path?
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
// now we can look up our model at self.model[indexPath.row]
}
关于ios - 在 MVVM 中处理来自 UITableViewCell 的 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36293991/