我通过情节提要设计了tableView,在一个单元格中我有一个按钮和一个Label。
按钮在Storyboard.in cellForRowAtIndexPath中具有tag-1和Label具有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;
}


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

最佳答案

因为您将按钮和标签分别标记为标签1和2,然后再次将标签值设置为indexpath.row,所以这就是造成问题的原因

 [topicButton setTag:indexPath.row ];


因此,只需为按钮和标签设置其他一些标记值(例如1000)即可。

然后您访问

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

10-08 05:58
查看更多