Ios 为什么UITableViewCell的子视图添加不正确?
我有个问题。 我实现了一个表视图。在Ios 为什么UITableViewCell的子视图添加不正确?,ios,xcode,cocoa-touch,uitableview,Ios,Xcode,Cocoa Touch,Uitableview,我有个问题。 我实现了一个表视图。在didselectrowatinexpath方法中,我增加单元格的高度,并在该单元格的contentView中添加一个文本视图。但如果我向下滚动表格视图(例如10个单元格),我将再次看到相同的文本视图。 你能帮帮我吗 下面是一些代码,可以更好地理解这个问题: - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
didselectrowatinexpath
方法中,我增加单元格的高度,并在该单元格的contentView
中添加一个文本视图。但如果我向下滚动表格视图(例如10个单元格),我将再次看到相同的文本视图。
你能帮帮我吗
下面是一些代码,可以更好地理解这个问题:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(selectedIndex == indexPath.row)
{
return CELL_HEIGHT * 5;
}
return CELL_HEIGHT;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:TRUE];
UITableViewCell *cell = [aTableView cellForRowAtIndexPath:indexPath];
if (selectedIndex == indexPath.row)
{
selectedIndex = -1;
[[cell.contentView viewWithTag:COOL_TAG] removeFromSuperview];
}
else
{
UITableViewCell *previousCell = [aTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:selectedIndex inSection:0]];
if ([previousCell.contentView viewWithTag:COOL_TAG])
{
[[previousCell.contentView viewWithTag:COOL_TAG] removeFromSuperview];
}
selectedIndex = indexPath.row;
UITextView *text = [[UITextView alloc] initWithFrame:CGRectMake(10, 45, 255, 180)];
[text.layer setBackgroundColor:[[UIColor whiteColor] CGColor]];
[text.layer setBorderColor:[[UIColor grayColor] CGColor]];
[text.layer setBorderWidth:1.0f];
[text.layer setCornerRadius: 8.0f];
[text.layer setMasksToBounds:YES];
[text setEditable:NO];
text.text = [questionArray objectAtIndex:indexPath.row];
text.tag = COOL_TAG;
[cell.contentView addSubview:text];
}
[tableView beginUpdates];
[tableView endUpdates];
}
提前谢谢 在viewdidload中创建textview,并将其添加到CellForRow方法中的tableview单元格。这可能会解决您的问题问题在于单元格被重用。因此,当您向下滚动添加textview的单元格时,它将在另一行中重复使用 我认为解决这个问题的最好方法是在cellForRowAtIndexPath方法中将textview添加到单元格中 然后需要创建一个数组,在其中定义行是否应显示textview。然后在didselect方法中,更改数组值并更新表
请注意,检查应在CellForRowatineXpath中的if(cell==nil)检查之外进行,否则不会为重用的单元格调用该检查。请尝试此代码,因为在您的情况下,单元格将被重新使用 静态NSString*CellIdentifier=@“YourCell”
不确定。它只是在表视图初始化之后添加文本视图。我需要在用户点击cell时添加它..你只需在DidselectRow方法中添加文本视图变量,而不是cellForRow。它可以正常工作。我刚刚在if(cell==nil){..中测试了所有单元格
YourCell *cell = (YourCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"YourCell" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (YourCell *) currentObject;
break;
}
}
}