UITableViewCell-设置单元格的最佳位置 [英] UITableViewCell - Best place to set up the cell
问题描述
我一直在研究UITableViewController中的自定义单元格,方法是先拥有一个基本单元格(BaseCell-UITableViewCell的子类),然后再拥有BaseCell的子类(Sub1Cell,Sub2Cell,这两个都是BaseCell的子类).
I've been playing around with custom cells in a UITableViewController by have a base cell (BaseCell - subclass of UITableViewCell) and then subclasses of BaseCell (Sub1Cell, Sub2Cell, both subclasses of BaseCell).
因为子类具有某些相同的功能,所以如果我将它们完全设置在其中
Because the subclasses share some of the same features, if I set them up completely in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
我开始为每种单元格类型重复代码.将通用设置代码放在实际的自定义UITableViewCell类中是否合适?目前,我已经编写了一种简单的设置方法:
I start to repeat code for each cell type. Is there a good place, and is it good practice, to put generic set up code inside the actual custom UITableViewCell class? Currently I've written a simple setup method:
- (void)setupCell
{
self.picture.layer.cornerRadius = 5.0f;
self.picture.layer.masksToBounds = YES;
self.picture.layer.borderColor = [[UIColor lightGrayColor] CGColor];
self.picture.layer.borderWidth = 1.0f;
}
一旦创建了单元格,我就一直在调用它:
I've just been calling this once I create my cell:
Sub1Cell *cell = [tableView dequeueReusableCellWithIdentifier:statusCellIdentifier];
[cell setupCell];
我可以使用一种可以自动调用的方法吗?我尝试了-(void)prepareForReuse,但是很显然,它不会每次都被调用,只有在单元被重用时才会被调用.
Is there a method I can use that will be called automatically? I tried -(void) prepareForReuse but it, obviously, isn't called every time, and only when cells are being reused.
有什么建议可以解决此问题的最佳方法吗?
Any advice on the best way to go about this?
似乎每次我呼叫tableView:cellForRowAtIndexPath
时都会被呼叫.我对创建自定义单元格的正确方法感到困惑.我应该按照以下方式做些事情吗?
It seems is actually being called every time I call tableView:cellForRowAtIndexPath
. I was a bit confused with the correct way to create a custom cell. Should I be doing something along the lines of:
Sub1Cell *cell = [tableview dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[Sub1Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
[cell setupCell];
}
如果我对传递的样式不做任何事情,会影响我的自定义单元格吗?
If I don't do anything with the style passed, will it affect my custom cell?
推荐答案
您可以在单元格子类中使用awakeFromNib
.从情节提要中的原型创建新的单元格时将调用此方法,但在重复使用某个单元格时将不调用此方法.
You can use awakeFromNib
in your cell subclasses. This will be called when a new cell is created from the prototype in your storyboard, but not when a cell is re-used.
如果您使用的是原型,那么整个if(cell == nil)事情都会消失,UITableView会在出队方法中为您处理所有这些事情.
If you are using prototypes then the whole if (cell == nil) thing goes away, UITableView handles all that for you within the dequeue method.
这篇关于UITableViewCell-设置单元格的最佳位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!