【发布时间】:2013-06-29 02:20:05
【问题描述】:
我正在开发一个将 XML 文件解析为 UITableView 的 iPhone 应用程序。它列出了 XML 文件中项目的所有标题,我试图让单元格展开并在选择指定单元格时添加所选项目的正文内容。
我可以让单元格正确展开,但是当我没有运气将正文内容添加为子视图时。在cellForRowAtIndexPath 填充单元格时,我可以添加正文内容,它显示正常。
我的问题是,如何在选中单元格后添加子视图?
我的 cellForRowAtIndexPath 函数,带有“正在运行”的 bodyLabel 注释掉:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = @"Cell";
issue *curIssue = [[parser issues] objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
CGRect nameFrame = CGRectMake(0,2,300,15);
UILabel *nameLabel = [[UILabel alloc] initWithFrame:nameFrame];
nameLabel.tag = 1;
nameLabel.font = [UIFont boldSystemFontOfSize:12];
[cell.contentView addSubview:nameLabel];
CGRect bodyFrame = CGRectMake(0,16,300,60);
UILabel *bodyLabel = [[UILabel alloc] initWithFrame:bodyFrame];
bodyLabel.tag = 2;
bodyLabel.numberOfLines = 10;
bodyLabel.font = [UIFont systemFontOfSize:10];
bodyLabel.hidden = YES;
[cell.contentView addSubview:bodyLabel];
}
UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:1];
nameLabel.text = [curIssue name];
UILabel *bodyLabel = (UILabel *)[cell.contentView viewWithTag:2];
bodyLabel.text = [curIssue body];
return cell;
}
这是我的heightForRowAtIndexPath 函数,我试图在其中添加子视图。尝试执行时,我在尝试分配 *bodyLabel 元素时收到 EXC_BAD_ACESS 异常。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger defCellHeight = 15;
NSInteger heightModifier = 10;
if([self cellIsSelected:indexPath]){
return defCellHeight * heightModifier;
}
return defCellHeight;
}
我的didSelectRowAtIndexPath 函数,它允许细胞生长/收缩:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
BOOL isSeld = ![self cellIsSelected:indexPath];
NSNumber *seldIndex = [NSNumber numberWithBool:isSeld];
[selectedIndexes setObject:seldIndex forKey:indexPath];
UILabel *label = (UILabel *)[tableView viewWithTag:2];
label.hidden = NO;
[curIssView beginUpdates];
[curIssView endUpdates];
}
最后,cellIsSelected 帮助函数,如果单元格被选中,则返回 true:
-(bool) cellIsSelected:(NSIndexPath *)indexPath
{
NSNumber *selIndex = [selectedIndexes objectForKey:indexPath];
return selIndex == nil ? FALSE : [selIndex boolValue];
}
您可以找到完整的源文件here。
【问题讨论】:
标签: iphone ios objective-c uitableview subview