首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UITableView:相同的单元格,多个模型对象

UITableView:相同的单元格,多个模型对象
EN

Stack Overflow用户
提问于 2016-06-16 17:04:22
回答 1查看 248关注 0票数 1

在使用UITableView & UICollectionView的同时,我正在研究如何编写模块化、干净的代码,我发现了Objc.io关于编写轻量级ViewControllers的很好的博客。在遵循作者给出的实践时,我想到了一个关于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.

有人能解释一下这是什么意思吗?我知道这是离题的,但它可能会帮助一些人写更好的代码。

EN

回答 1

Stack Overflow用户

发布于 2016-06-16 18:34:32

这类似于引入ViewModel或ViewAdapter。一个简单的例子是单元格显示任何项目的描述。比方说,如果你给单元一个用户,它会显示他/她的全名。如果你发送邮件,它会显示主题。关键是,计算单元并不关心给它的确切内容(用户或邮件)。它只需要每个项目的描述,所以它需要从不同类型的的每个单独的模型中提取描述字符串的。那是ViewModel。

而不是: Cell => User或Cell =>新闻。用法: Cell => ViewModel =>用户或Cell => ViewModel =>新闻。代码示例:

代码语言:javascript
复制
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 "";
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37854600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档