viewWithTag故障。

时间:2013-01-30 09:58:23

标签: iphone ios objective-c uiview

我通过故事板设计了tableView,在一个单元格中我有一个按钮&一个标签。 按钮是标签-1&标签在storyboard上有标签-2。在cellForRowAtIndexPath我正在访问这些如下所示

- (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时,我又重新加载了这个,但这次两行它运行良好。但对于第三行,它返回UIButton而不是UILabel,用于此行UILabel *topicScoreLabel=(UILabel *)[cell viewWithTag:2];&因此,它给出了异常“无法识别的选择器”[UIButton setText]“”;

2 个答案:

答案 0 :(得分:4)

因为你得到的按钮和标签为标签1和2,然后你又将标签值设置为indexpath.row,这就是为什么它会产生问题

 [topicButton setTag:indexPath.row ];

所以只需将一些其他标记值设置为按钮并标记为1000。

然后你访问

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

答案 1 :(得分:0)

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