ios - UITableViewCell 和 UIViewController 的简洁开发模式

标签 ios objective-c uitableview

我有一个 NIB,它包含一个用作导航 View 的 UIView 和一个 UITableView。 NIB 将 UITableViewController 称为它的所有者。

我想把我的关注点分开:我的单元格都将管理它们自己更深层次的交互,但是如果说,我想呈现一个 UIImagePickerController,我需要使用 UIViewController

传统上,我的理解是委派是这种架构品牌的最佳选择,但我的 UITableView 类正在管理单元格的呈现,这些单元格本身管理着它们自己的交互。那么我是否要委托(delegate)给 tableview(它不是 viewcontroller),它委托(delegate)给 UIViewController?我如何做这样的事情才能使其尽可能低调?

最佳答案

所以,我解决了这个问题。事实证明,一个好的方法是这样的:

1) 细胞将有一个协议(protocol)。该协议(protocol)将以表达对常驻 View Controller 的愿望的方法为特色。更具体地说:

/* .h file of cell */
@protocol LoItemViewCellDelegate <NSObject>

@optional
- (void)cell:(LoItemViewCell *)cell wantsToPresentViewController:(id)viewController;
- (void)cell:(LoItemViewCell *)cell wantsToPresentActionSheet:(UIActionSheet *)actionSheet;

@end

2) 单元格必须可以直接通过其委托(delegate)访问 View Controller 。否则,您将创建一个变得难以驾驭的逻辑三明治。 (例如 cellview->tableview->viewcontroller)

3) 然后在你的单元格中任何你需要的地方调用这个方法:

/* Inside some method in cell .m */
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:sourceType];
imagePicker.delegate = self;

[self.delegate cell:self wantsToPresentViewController:imagePicker];

4) 然后,您的代理可以自由地以任何它希望的方式实现这些方法。

/* Delegate view controller */
- (void)cell:(LoItemViewCell *)cell wantsToPresentViewController:(id)viewController
{
    [self presentViewController:viewController animated:YES completion:nil];
}

通过这种方式,您只传递单元无法自行处理的内容,而其他所有内容(控制逻辑等)则保留在单元中。因此,例如,在这个例子中,我将一个 UIImagePickerController 传递给我的委托(delegate)以仅显示,而我在我的单元格内进行该 Controller 的所有管理,因为我的单元格是唯一的一段代码明确给出了该死的选择器想要做什么。

非常干净,我非常推荐这种方法。

关于ios - UITableViewCell 和 UIViewController 的简洁开发模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22188105/

相关文章:

ios - 从 UIPickerView 接收输入时如何更新 UITextField?

带有 Xamarin 的 iOS AutoLayout 在 Visual Studio 2013 中仅使用 C# 代码,没有 XCode 或 Interface Builder

ios - 从 Collection View Xcode 中删除 Collection View Cell

ios - 使 NSArray IBInspectable

objective-c - 标签栏项目第三次触摸 TableView 不滚动到顶部

ios - 更改 UItableView 高度后,我的滚动不再起作用。无法到达底部数据

ios - 由于某种原因,UIBezierPath 轮廓不断出现在 View 周围

ios - 将多个值传递给 nextview Controller

iphone - UITableView背景颜色不改变

ios - 解析奇怪的 JSON - swift