【问题标题】:UITableView: Same cell, Multiple model objects(MVC)UITableView:同一个单元格,多个模型对象(MVC)
【发布时间】:2016-10-17 16:47:48
【问题描述】:

在使用UITableViewUICollectionView 时,我正在研究编写模块化干净代码,我发现Objc.io 写的关于编写更轻量级视图控制器的不错的博客。在遵循作者给出的做法时,我想出了一段关于Same Cell type and Multiple Model Object 的内容,但没有详细说明,只是描述性的。 我只是想问有没有人建议我们如何以更好的模块化方式实现这一目标? 这段话是这样说的,

In cases where we have multiple model objects that can be presented using the same cell type, we can even go one step further to gain reusability of the cell. First, we define a protocol on the cell to which an object must conform in order to be displayed by this cell type. Then we simply change the configure method in the cell category to accept any object conforming to this protocol. These simple steps decouple the cell from any specific model object and make it applicable to different data types.

谁能解释一下这是什么意思? 我知道这不是主题,但它可能会帮助某人编写更好的代码。

【问题讨论】:

    标签: ios uitableview design-patterns model-view-controller uicollectionview


    【解决方案1】:

    这类似于引入 ViewModel 或 ViewAdapter。一个简单的例子是一个单元格显示任何项目的描述。假设你给单元格一个用户,它会显示他/她的全名。如果你给一个邮件,它会显示主题。关键是单元不关心到底给了它什么(用户或邮件)。它只需要每个项目的描述,因此它需要帮助它从不同类型的每个模型中提取描述字符串的东西。这就是 ViewModel。

    然后代替:单元 => 用户或单元 => 新闻。使用:Cell => ViewModel => User 或 Cell => ViewModel => News。代码示例:

    class ViewModel {
    
        private Object _item;
    
        public ViewModel(Object item) {
            _item = item;
        }
    
        public String getDescription() {
            if (_item instanceof User) {
                return ((User)_item).getFullName();
            } else if (_item instanceof Mail) {
                return ((Mail)_item).getSubject();
            }
            return "";
        }
    }
    

    【讨论】:

    • 这里不是根据模型的类型来编写条件代码。这里要求声明一些接口(用 java 术语)或协议(用 ObjC 术语)。
    • 相同的概念,不同的实现方式。上面的 sn -p 是使用 Adapter 最简单的方法之一。我以为你只是想了解这个想法......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多