ios - 多个 UIViewControllers 同时出现在屏幕上

标签 ios cocoa-touch uiviewcontroller

我在多个地方读到,一次只有一个 UIViewController 应该出现在屏幕上。但我不太明白如何完成我需要的东西。

想象一下天气应用程序。有一个带有 ScrollView 的单个 View Controller ,向其中添加了多个 View (天气面板)。想必这些都是由主UIViewController添加和管理的,它还负责滚动等。

但想象一下,这些天气面板中的每一个都是一个 CarView,每个都有关于特定类型汽车的数据,以及一些用于编辑该数据的控件。

如果有一系列 CarViewControllers,每个都有一个可以操作的 Car 属性,这不是很有意义吗?每个 CarViewController 将负责它的汽车数据对象,它的 View ,并将它们粘合在一起,主视图 Controller 将简单地负责将每个 carViewController.view 添加到它的 ScrollView 。

这不是更好的可重用性和封装性吗?更不用说更方便了。

最佳答案

我认为这只是归结为它是否会让您的生活更轻松。我喜欢做的一种替代方法是只编写专门用于显示“概念”模型(如汽车)的复合 UIView 子类,然后在其上编写类别以使用特定模型实现填充 View 信息。这样,您可以在更改模型时重新使用 View ,但仍然可以避免一些逻辑弄乱 View Controller 。我尝试为诸如使用 UISegmentedControl 或其他东西切换的完全不同的 View 之类的东西保留一个 View Controller 。

编辑:UIView 及其填充类别的示例。

@interface CarView : UIView

@property (strong) UILabel *modelLabel;
@property (strong) UILabel *makeLabel;
@property (strong) UILabel *yearLabel;
//etc

@end

然后你有一个特定于模型的类别,而 View 上的类别确实更适合 Controller 层;虽然有点违反 MVC,但我认为从责任分配的角度来看它工作得很好,不会将您的主视图实现与任何数据实现耦合,并使您的 View Controller 更精简,所以我认为值得权衡。

@interface CarView (CarEntityPopulating)

- (void)populateFieldsWithEntity:(NSManagedObject *)entity;

@end

@implementation CarView (CarEntityPopulating)

- (void)populateFieldsWithEntity:(NSManagedObject *)entity
{
    self.modelLabel.text = [entity valueForKey:@"name"];
    self.makeLabel.text = [[entity valueForKey:@"make"] valueForKey:@"name"];
    self.yearLabel.text = [[entity valueForKey:@"year"] stringValue];
    //etc....
}

关于ios - 多个 UIViewControllers 同时出现在屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12681242/

相关文章:

ios - 在 iOS 中切换 UIViewController

ios - 保持 UIView 从一个 Controller 到另一个 Controller

iOS 10 错误多次记录导致应用程序挂起

ios: 在 64 位设备中崩溃

iphone - CGAffineTransform Rotate 旋转次数而不是角度

ios - 如何将本地 html 文件加载到 UIWebView

ios - 如何在 Swift 的 TableViewController 中向自动后退按钮添加 Action

ios - 应用程序因 Info.plist 文件麦克风中缺少用途字符串而被拒绝,但我无法在 info.plist 中添加描述

iphone - 如何使用 GCD 在后台定期运行代码块?

iphone - 如何通过 HTTP 将大型 .m4v 视频文件流式传输到我的 iOS 应用程序?