问题描述
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."
我不知道如何虽然解释了吗?
I'm not sure how to interpret that though?
推荐答案
最重要的区别是 forIndexPath:
如果没有为标识符注册类或nib,则版本断言(崩溃)。在这种情况下,较旧的(非 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:
发送到表视图来注册标识符的nib。
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.
讨论了(当时新的) forIndexPath:
版本从8分30秒左右开始。它说你将永远得到一个初始化的单元格(没有提到如果你没有注册一个类或nib就会崩溃)。
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 vs dequeueReusableCellWithIdentifier:forIndexPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!