如何在配置自定义UITableViewCell时传递参数

3
我是一名有用的助手,可以为您翻译文本。

我有一个自定义的UITableViewCell,我们称之为CustomCell。我所需要的就是在创建它时传递一个参数,比如一个NSURL

这是我在ViewController中迄今为止所做的:

viewDidLoad中:

[myTableView registerClass: [CustomCell class] forCellReuseIdentifier: @"CustomItem"]

在`tableView:cellForRowAtIndexPath:`方法中
static NSString *myIdentifier = @"CustomItem"
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:myIdentifier] 

所有这些都很好,但我需要配置此单元格与此NSURL,但仅一次,而不是每次调用cellForRowAtIndexPath时。 我注意到在CustomCell中的initWithStyle:reuseIdentifier:只被调用一次,但我如何在此调用中添加NSURL

你在任何数组中保存了URL吗? - Himanshu Joshi
我可以在cellForRowAtIndexPath中访问URL,我需要设置它一次,但只有一次,而不是每次调用cellForRowAtIndexPath时都设置。这可能吗? - Odd
请澄清一下“set it once”是什么意思? - Himanshu Joshi
我不想在每次调用cellForRowAtIndexPath时都执行[cell setURL: url],只想在初始化时执行。 - Odd
只需在自定义单元格的“标签”中添加“url”即可。 - Himanshu Joshi
显示剩余4条评论
2个回答

4

您只需在viewDidLoad中加载一个NSArray。在cellForRowAtIndexPath:中,您将从NSArray中添加URL并将其插入到UITableViewCell中。

static NSString *myIdentifier = @"CustomItem"
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:myIdentifier]
[cell.labelURL setText:_arrayURLs[indexPath.row]];

您需要做的就是在您的CustomCell中添加一个名为labelURL的新属性,并将其与UIStoryboard或xib文件中的UILabel连接起来。
请注意,您不能仅仅设置一次。UITableViewCell将重用它的UITableViewCells,并且会多次给同一个对象设置另一个值。这就是为什么您必须这样做而不仅仅是一次。

好的,这更像是对我的问题的回答:“你不能只设置一次”,很公平。 URL 的目的是加载图片,我希望 CustomeCell 在图片加载后执行 UIViewAnimation,我该怎么做? 我已经有了所有动画和加载等代码,但现在每次调用 cellForRowAtIndexPath 时都要重新加载图片 :P - Odd
你应该使用 NSURLConnection sendAsynchronousRequest:queue:completionHandler: 在后台执行此操作。你可以在 CustomCell 中创建一个方法,如果通过点击单元格选择了单元格,则单元格已经知道其来自 labelURLNSURL。如果你没有太多的图片,你也可以在加载 UITableViewController 时异步加载它们,并将它们保存到字典中,这样一切都会更容易,但看起来你不仅仅是在谈论10个 UIImages - Alex Cio
因为重用单元格的概念,单元格不可能拥有自己的变量,对吗?所以我真正需要的是让数据源处理这个问题? - Odd
因为重用的原因,这种方式可能会变得复杂。但是你知道你的 UITableViewCells 的顺序,所以你可以在 didSelectRowAtIndexPath 中获取选定的行,并向特定的单元格添加 UIImage - Alex Cio

1

应该使用cellForRowAtIndexPath:重用相同类型的UITableViewCell。如果您希望property保持不变,它应该放在区域A中。如果您希望它在每个单元格中更改,则应将其放在区域B中。

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CustomCell";
    CustomCell *cell = 
      [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell) {
        cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault 
                                reuseIdentifier:CellIdentifier];
       // (A) everything inside here happens once 
       // for example

       cell.textLabel.backgroundColor = [UIColor redColor];
    }

    // (B) everything here happens every reuse of the cell
    // for example

    cell.textLabel.text = [NSString stringWithFormat:@"%li",
                            (long)indexPath.row];
    return cell;
}

由于[feedTableView registerClass:[CutomCell class] forCellReuseIdentifier:@"CustomItem"],单元格永远不会为空,因此A区域永远不会被调用... - Odd
在这种情况下,如果您正在创建静态单元格,似乎可以将其放在该方法内部? - user1641587

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接