ios - 在 MVVM 中处理来自 UITableViewCell 的 Action

标签 ios objective-c mvvm uikit reactive-cocoa

所以我有这个 BaseCell类也有这个 BaseCellViewModel .当然,除此之外还有一些FancyViewControllerFancyViewModel .这里的情况是 BaseCellUIButton在它上面触发这个 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 上注册一些东西呢?实际监听执行RACCommandBaseCellViewModel

最佳答案

单元格可以通过几种方式与 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/

相关文章:

iphone - UIActionSheet 像按钮

c# - 使用 MVVM 在 DataGrid 中级联 ComboBox

c# - PropertyChanged 未按预期工作

ios - UIView翻转动画问题

ios - 放弃 iOS 4 支持

c# - 带有(一点点)Unity 3D 的 iOS 项目?

ios - 在 iOS 项目中使用开源 C 库 (GRIB API)

c# - 将按钮命令绑定(bind)到非静态属性

ios - 尝试删除 UITableViewCell

ios - 如何通过触摸单元格内的按钮快速编辑文本字段