UITableView中的手风琴效果

时间:2011-11-30 11:34:09

标签: objective-c cocoa-touch uitableview

当我选择它时,我想在表格视图中展开一个单元格。最初应该如下所示:

在扩展时,它应该提供更多这样的细节:

这就是我最初创建单元格的方式:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * MyIdentifier = @"MyIdentifier";
    UITableViewCell * cell = [self.table dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MyIdentifier] autorelease];
        cell.textLabel.frame = CGRectMake(0, 0, cell.textLabel.frame.size.width, 
        cell.textLabel.frame.size.height);
 }
 id key = [[articles allKeys] objectAtIndex:indexPath.section];
 cell.textLabel.text =@"TitleTitleTitle";        
 cell.detailTextLabel.text=@"DeatailDeatailDeatailDeatailDeatailDeatailDeatailDeatailDeatai";
 return cell;
}

1 个答案:

答案 0 :(得分:1)

我在github

发布了示例代码

您的tabelView:cellForRowAtIndexPath:看起来像这样。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * MyIdentifier = @"MyIdentifier";
    UITableViewCell * cell = [self.table dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MyIdentifier] autorelease];
        cell.textLabel.frame = CGRectMake(0, 0, cell.textLabel.frame.size.width, 
                                          cell.textLabel.frame.size.height);
    }
    id key = [[articles allKeys] objectAtIndex:indexPath.section];
    cell.textLabel.text =@"TitleTitleTitle";        
    cell.detailTextLabel.text=@"DeatailDeatailDeatailDeatailDeatailDeatailDeatailDeatailDeatai";


    //SEE MY NOTE BELOW
    if([indexPath isEqual:selectedIndexPath]){
        cell.textLabel.numberOfLines=0;
        cell.detailTextLabel.numberOfLines=0;

        CGSize constraintSize;
        constraintSize.width = cell.textLabel.frame.size.width;
        constraintSize.height = MAXFLOAT;
        cell.textLabel.frame = [cell.textLabel.text sizeWithFont:cell.textLabel.font constrainedToSize:constraintSize];

        constraintSize.width = cell.detailTextLabel.frame.size.width;
        constraintSize.height = MAXFLOAT;
        cell.detailTextLabel.frame = [cell.detailTextLabel.text sizeWithFont:cell.detailTextLabel.font constrainedToSize:constraintSize];
    } else {
        cell.textLabel.numberOfLines=1;
        cell.detailTextLabel.numberOfLines=1;
    }
    return cell;
}

<强> BUT
您还需要tableView:heightForRowAtIndexPath:中动态单元格的高度,因此您应该将大小调整部分重构为辅助方法,将2个标签的大小和单元格的高度写入ivars,调用方法从tableView:heightForRowAtIndexPath:开始,使用此处的单元格高度和tabelView:cellForRowAtIndexPath:

中的标签大小