【问题标题】:viewWithTag malfunction.viewWithTag 故障。
【发布时间】:2026-02-25 12:15:02
【问题描述】:

我通过情节提要设计了 tableView,在一个单元格中我有一个按钮和一个标签。 按钮在 storyboard.in cellForRowAtIndexPath 上有 tag-1 和标签有 tag-2 我正在访问这些,如下所示

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@" i am back in cellForRowAtIndexPath");  

    static NSString *CellIdentifier = nil;
   // UILabel *topicLabel;
    NSInteger rows=indexPath.row;
    NSLog(@"row num=%i",rows);
    if (rows % 2==0)
    {
        CellIdentifier=@"LeftTopicCell";
    }
    else
    {
        CellIdentifier=@"RightTopicCell";

    }

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    UIButton *topicButton=(UIButton *)[cell viewWithTag:1];
    UILabel  *topicScoreLabel=(UILabel *)[cell viewWithTag:2];

    NSString *topicNameLabel=[[NSString alloc]init];

    //some logic processing


            topicNameLabel= topicItem.topicTitle;

            [topicButton setTitle:topicNameLabel forState:UIControlStateNormal];
        [topicButton setTag:indexPath.row ];
            [topicButton setTitle:topicNameLabel forState:UIControlStateHighlighted];
            [topicButton addTarget:self action:@selector(topicButtonSelected:) forControlEvents:UIControlEventTouchDown];

        [topicScoreLabel setText:[NSString stringWithFormat:@"%d/%d",correctAnswers,[answerResults count]]];
    }

    return cell;
}

第一次它运行良好,但是当我回到这个视图控制器时,我再次重新加载了它,但这次它运行良好的两行。但是对于第三行,它返回 UIButton 而不是 UILabel 对于这一行 UILabel *topicScoreLabel=(UILabel *)[cell viewWithTag:2]; & 因此它给出异常“无法识别的选择器“[UIButton setText]”;

【问题讨论】:

  • 您确定在 LeftTopicCell 和 RightTopicCell 单元格中都正确设置了标签吗?
  • 您在哪里将按钮和标签作为子视图添加到您的表格中?
  • 是的,标签在 20 次以上肯定是正确的
  • @Rajneesh071:添加到故事板上
  • 因为你正在设置标签 [topicButton setTag:indexPath.row ];现在标签正在改变

标签: iphone ios objective-c uiview


【解决方案1】:

因为您将按钮和标签设置为标记 1 和 2,然后再次将标记值设置为 indexpath.row,这就是它产生问题的原因

 [topicButton setTag:indexPath.row ];

所以只需为您的按钮和标签设置一些其他标记值,例如 1000。

然后你访问

UIButton *topicButton=(UIButton *)[cell viewWithTag:1000];
UILabel  *topicScoreLabel=(UILabel *)[cell viewWithTag:1001];

【讨论】:

    【解决方案2】:

    我得到了答案,因为我正在根据行号通过 cellForRowAtIndexPath 中的 setTag 方法更新按钮标签,它将标签设置为按钮为 2 这就是它返回 UIButton 的原因

    【讨论】: