【问题标题】:Adding UILabel to UIImageView in CellForRow将 UILabel 添加到 CellForRow 中的 UIImageView
【发布时间】:2013-05-16 15:34:28
【问题描述】:

我在 StoryBoard“CategoryCell”中有一个 customCell,我有 UIImageView 和单元格,它也是单元格的一部分,也绑定在 StoryBoard 中。 UIImageView 用纯黄色填充。我打算给这个纯黄色图像添加一个标签,标签因单元格而异。

下面的代码最初运行良好,但是当我滚动 tableView 时,我看到图像中的标签变得混乱,就像它试图在文本顶部写入新文本一样。我认为它再次点击 cellForRow 并且它正在添加新标签,我怎样才能让它不在旧标签之上创建新标签?

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

if([tableView isEqual:wordsTableView])
{
    CategoryCell *cell = [CategoryTableView dequeueReusableCellWithIdentifier:@"CategoryCellIdentifier" forIndexPath:indexPath];
    if(!cell)
        cell = [[CategoryCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:@"CategoryCellIdentifier"];

    NSString *text = [[theCategories objectAtIndex:indexPath.row] uppercaseString];

    //Add label now
    catLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 40, 20)];
    catLabel.text = text;
    [cell.codeImageView addSubview:catLabel];

   return cell;
 }

【问题讨论】:

    标签: ios5 uitableview uiimageview uilabel


    【解决方案1】:

    你可以给标签一个标签,并用它来检查它是否存在,然后再创建它:

    UILabel *catLabel = [cell.codeImageView viewWithTag:100];
    if (nil == catLabel) {
        catLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 40, 20)];
        catLabel.tag = 100;
        [cell.codeImageView addSubview:catLabel];
    }
    catLabel.text = text;
    

    虽然如果它变得更复杂,我可能会考虑子类化 UITableViewCell 并使用 xib 来实例化标签。

    【讨论】:

    • 它有效,谢谢 - 我知道它与标签有关。顺便说一句,CategoryCell 是 UITableViewCell 的子类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多