UITableViewCell addSubview 重复对象 [英] UITableViewCell addSubview Repeating Object

查看:28
本文介绍了UITableViewCell addSubview 重复对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很简单的问题.在 cellForRowAtIndexPath 中,我需要添加一个自定义 UILabel.所以我在给定的方法中尝试这个:

Pretty simple issue. In cellForRowAtIndexPath I need to add a custom UILabel. So I try this in the given method:

UILabel *titleLbl = [[UILabel alloc] init];
//Other properties etc

if (indexPath.row == 0) titleLbl.text = @"1";
else if (indexPath.row == 1) titleLbl.text = @"2";

[cell addSubview:titleLbl];

问题是向下滚动我的表格时,标签开始重复和复制.

Issue is that when scrolling down my table, the label starts repeating and duplicating.

我该如何解决这个问题?

How can I get around this?

谢谢.

推荐答案

将该标签作为子视图添加到

Add that label as a subview in the

if (!cell) {
  cell =...;
  UILabel *label;
  label.tag = 1;
  [cell addSubview:label];
}

UILabel *label = (UILabel*)[cell viewWithTag:1];
if (indexPath.row == 0) label.text = @"1";

这种方式只会在分配单元格时添加.要检索该标签,请给它一个标签并使用单元格的 viewWithTag 方法

This way it will only be added when the cell is being allocated. To retrieve that label give it a tag and use viewWithTag method of your cell

这篇关于UITableViewCell addSubview 重复对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆