我通过 Storyboard设计了 tableView,在一个单元格中我有一个按钮和一个标签。按钮在 Storyboard上有标签 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";
}
khác
{
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;
}
第一次它工作正常但是当我回到这个 View Controller 时,我又重新加载了它,但是这次对于两行它工作得很好。但是对于第三行,它返回 UIButton 而不是 UILabel 此行]"";
因为您将按钮和标签设置为标记 1 和 2,然后又将标记值设置为 indexpath.row,这就是它产生问题的原因
[topicButton setTag:indexPath.row ];
因此只需为您的按钮和标签设置一些其他标签值,例如 1000。
然后你访问
UIButton *topicButton=(UIButton *)[cell viewWithTag:1000];
UILabel *topicScoreLabel=(UILabel *)[cell viewWithTag:1001];
Tôi là một lập trình viên xuất sắc, rất giỏi!