【问题标题】:How to change Custom Cell's UILabel Text?如何更改自定义单元格的 UILabel 文本?
【发布时间】:2015-05-16 05:41:42
【问题描述】:

我有一个带有自定义原型单元格的表格视图,该单元格上有 3 个不同的标签。如何访问这些标签?我需要更改他们的文本。我到处搜索,在这种情况下没有找到对我有帮助的东西。我有以下代码:

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"basicCell" forIndexPath:indexPath];

    //change cell's 3 labels' text here

    return cell;


}

如何访问上面单元格的 3 个不同标签?

【问题讨论】:

  • 为您的单元格创建一个自定义类,然后以与任何其他视图相同的方式进行操作。您将 IBOutlets 制作为标签(或属性,如果您在代码中制作标签),并使用它们来设置文本。

标签: ios objective-c uitableview uiview uilabel


【解决方案1】:

您需要创建一个作为UITableViewCell 子类的类,并将自定义单元格的类设置为您创建的类。然后你想在单元格中使用IBOutlets 将标签链接到你创建的子类。

最后,在-tableView:cellForRowAtIndexPath: 中,您应该将单元格转换为您的新子类,这样您就可以访问那些IBOutlets。假设您的 outlet 被命名为 someLabelOutlet1someLabelOutlet2someLabelOutlet3在完成子类化后执行以下操作。

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

    SomeTableViewCellSubclass *cell = (SomeTableViewCellSubclass *)[tableView dequeueReusableCellWithIdentifier:@"basicCell" forIndexPath:indexPath];

    cell.someLabelOutlet1.text = @"sometext"
    cell.someLabelOutlet2.text = @"sometext"
    cell.someLabelOutlet3.text = @"sometext"

    return cell;
}

【讨论】:

  • 你不要在那里做。您需要创建一个新的UITableViewCell 子类。
  • 现在表格什么也不显示了:(
  • 您是否将标签链接到UITableViewCell 子类?
  • 等等,我们不是也得改变方法的返回类型吗?
  • 不,当然不是。检查您是否真的正确地对其进行了子类化并正确地执行了所有操作。
【解决方案2】:

cellForRowAtIndexPath,你可以访问这些标签

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    CustomCell *cell =[tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
    if (!cell) {
    [tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:@"CustomCell"];
    cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
    // set common properties here
    cell.lbl1.textColor=[UIColor whiteColor];
    cell.lbl1.backgroundColor=[UIColor redColor];
    cell.lbl1.font=[UIFont fontWithName:@"Verdana" size:16.0];
    }
    cell.lbl1.text=@"lbl1Txt";
    cell.lbl2.text=@"lbl2Txt";
    cell.lbl3.text=@"lbl3Txt";
    return cell;
}

【讨论】:

    猜你喜欢
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多