gpt4 book ai didi

iphone - 将 subview 添加到单元格 contentView

转载 作者:行者123 更新时间:2023-11-29 04:41:43 25 4
gpt4 key购买 nike

所以我有以下代码:

static NSString *CellIdentifier = @"RecommendationCell";

UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TableViewCell"] autorelease];
}

UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[indicator setCenter:CGPointMake(0, 15)];
[indicator startAnimating];
[indicator hidesWhenStopped];

UILabel *someLabel.........


UIView *containerView = [[UIView alloc] initWithFrame:CGRectZero];
[containerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
[containerView setAutoresizesSubviews:YES];
[containerView setBackgroundColor:[UIColor clearColor]];
[containerView addSubview:indicator];
[containerView addSubview:someLabel];
[containerView setFrameSize:CGSizeMake(indicator.frameWidth+self.loadingGeniusLabel_.frameWidth, 30)];
[containerView setCenter:CGPointMake(cell.contentView.center.x, 15)];

[cell.contentView addSubview:containerView];

[indicator release];
[containerView release];

return cell;

我的问题是,上面的代码高效/干净吗?我问的原因是因为如果我们获得的单元格来自可重用的甲板,那么它将具有 UIActivityIndi​​cator 和必要的 View ,对吗?仅当我分配新单元格时(即:当单元格 == nil 时),我是否只需要添加 subview ?

最佳答案

is the code above efficient/clean?

没有

if the cell that we get is from the reusable deck, then it would have the UIActivityIndicator and the necessary view in it right

是的,但由于您使用的是通用 UITableViewCell,因此添加一次后将无法访问 UIActivityIndi​​cator。您需要创建 UITableViewCell 的子类才能有效地完成此操作。

Do I just have to add the subviews only if I am allocating a new cell (i.e: when the cell == nil)?

是的

只有在绝对需要的情况下才在 if (cell == nil) block 之外调用 addSubview,这是一个昂贵的方法调用,并且会严重影响滚动表格时的每秒帧数。

最好的选择是子类化 UITableViewCell。这样,您需要控制不同单元格的值/行为的任何对象/UIView(或 UIView 子类)都更适合作为 UITableViewCell 子类的属性。通过这样做,您可以在 xib 文件或单元设置(在 if 语句内)中实例化它们,然后只需更改每个单元的值(而不是每次创建新对象)。

Apple 的 TableView 编程指南对此进行了深入讨论: http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/AboutTableViewsiPhone/AboutTableViewsiPhone.html#//apple_ref/doc/uid/TP40007451

Apple 的示例项目展示了有效管理表格单元格的几种不同方法: https://developer.apple.com/library/ios/#samplecode/TableViewSuite/Introduction/Intro.html

关于iphone - 将 subview 添加到单元格 contentView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10288907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com