问题描述
dequeueReusableCellWithIdentifier 有两种重载,我正在尝试确定何时应该使用一种还是另一种?
There are two overloads for dequeueReusableCellWithIdentifier and I'm trying to determine when should I use one vs the other?
关于 forIndexPath 函数的 Apple 文档指出,此方法使用索引路径根据表格视图中单元格的位置执行附加配置."
The apple docs regarding the forIndexPath function states, "This method uses the index path to perform additional configuration based on the cell’s position in the table view."
我不知道如何解释?
推荐答案
最重要的区别是 forIndexPath:
版本断言(崩溃)如果您没有为标识符.在这种情况下,旧的(非forIndexPath:
)版本返回nil
.
The most important difference is that the forIndexPath:
version asserts (crashes) if you didn't register a class or nib for the identifier. The older (non-forIndexPath:
) version returns nil
in that case.
您可以通过将 registerClass:forCellReuseIdentifier:
发送到表视图来为标识符注册一个类.您可以通过将 registerNib:forCellReuseIdentifier:
发送到表视图来为标识符注册一个笔尖.
You register a class for an identifier by sending registerClass:forCellReuseIdentifier:
to the table view. You register a nib for an identifier by sending registerNib:forCellReuseIdentifier:
to the table view.
如果您在故事板中创建表格视图和单元格原型,故事板加载器会负责注册您在故事板中定义的单元格原型.
If you create your table view and your cell prototypes in a storyboard, the storyboard loader takes care of registering the cell prototypes that you defined in the storyboard.
第 200 场会议 - WWDC 2012 的 Cocoa Touch 的新功能 讨论了(当时 -new) forIndexPath:
大约 8 分 30 秒开始的版本.它说你总是会得到一个初始化的单元格"(没有提到如果你没有注册一个类或笔尖它会崩溃).
Session 200 - What's New in Cocoa Touch from WWDC 2012 discusses the (then-new) forIndexPath:
version starting around 8m30s. It says that "you will always get an initialized cell" (without mentioning that it will crash if you didn't register a class or nib).
视频还说它将是该索引路径的正确大小".大概这意味着它将在返回之前设置单元格的大小,通过查看表格视图自己的宽度并调用您的委托的 tableView:heightForRowAtIndexPath:
方法(如果已定义).这就是为什么它需要索引路径.
The video also says that "it will be the right size for that index path". Presumably this means that it will set the cell's size before returning it, by looking at the table view's own width and calling your delegate's tableView:heightForRowAtIndexPath:
method (if defined). This is why it needs the index path.
这篇关于何时使用 dequeueReusableCellWithIdentifier 与 dequeueReusableCellWithIdentifier : forIndexPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!