gpt4 book ai didi

iphone - 我应该如何将Subview添加到cell.contentView?

转载 作者:行者123 更新时间:2023-12-03 18:17:20 28 4
gpt4 key购买 nike

A(当新创建单元格时):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

CGRect frame = CGRectMake(0, 0, 160, 50);
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.textAlignment = UITextAlignmentRight;
label.text = @"9:00am";
[cell.contentView addSubview:label];
[label release];
}

return cell;
}

或 B(每次找到单元格时):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
static NSString *CellIdentifier = @"Cell";

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

CGRect frame = CGRectMake(0, 0, 160, 50);
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.textAlignment = UITextAlignmentRight;
label.text = @"9:00am";
[cell.contentView addSubview:label];
[label release];

return cell;
}

A还是B?谢谢!

更新解决方案(感谢您的回答):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{

static NSString *CellIdentifier = @"Cell";
UILabel *label;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

CGRect frame = CGRectMake(0, 0, 160, 50);
label = [[UILabel alloc] initWithFrame:frame];
label.textAlignment = UITextAlignmentRight;
label.tag = 1;
[cell.contentView addSubview:label];
[label release];
} else {
label = (UILabel *) [cell viewWithTag:1];
}

label.text = [NSString stringWithFormat:@"%d", [indexPath row]];

return cell;
}

最佳答案

一切都与性能有关。对于 A,您可以重用单元格及其所有 subview ,对于 B,您可以仅重用原始单元格并在每次迭代中添加一个新的 subview ,恕我直言,这不如 A re: 性能。

我说要么创建一个 UITableView 子类,要么使用解决方案 A。

关于iphone - 我应该如何将Subview添加到cell.contentView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3490433/

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