动态 UITableViewCell 每个 UILable 高度,支持纵向横向



我需要根据标签的内容创建一个单元格高度,并带有方向支持,目前已经尝试过并且适用于肖像,但不适用于横向,因此需要适用于两者的解决方案,所以如果有人可以请帮助我。

提前感谢您的努力。

这是我在表视图中的代码

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *arr = [arrData objectAtIndex:tableView.tag];    
    NSString *text = [arr objectAtIndex:indexPath.row];    
    CGSize constraint = CGSizeMake(contentWidth - (CELL_CONTENT_MARGIN * 2), 20000.0f);    
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:20] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];    
    CGFloat height = MAX(size.height, 44.0f);    
    return height + (CELL_CONTENT_MARGIN * 2);
}

自定义表视图单元格的外观。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    UILabel *label = nil;
    cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
        cell.accessoryView = nil;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        label = [[UILabel alloc] initWithFrame:CGRectZero];
        [label setLineBreakMode:NSLineBreakByWordWrapping];
        [label setNumberOfLines:0];
        [label setFont:[UIFont systemFontOfSize:20]];
        [label setTag:1];
        [label setBackgroundColor:[UIColor redColor]];                
        [[cell contentView] addSubview:label];
    }
    NSArray *arr = [arrData objectAtIndex:tableView.tag];
    NSString *text = [arr objectAtIndex:indexPath.row];
    CGSize constraint = CGSizeMake(contentWidth - (CELL_CONTENT_MARGIN * 2), 20000.0f);
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:20] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
    if (!label)
        label = (UILabel*)[cell viewWithTag:1];
    [label setText:text];
    [label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, contentWidth - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
    return cell;
}

heightForRowAtIndexPath中,您可以根据方向设置高度。当方向改变时,重新加载单元格。在heightForRowAtIndexPath使用此值检查方向,同时调用此方法-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration重新加载单元格。

所以你的heightForRowAtIndexPath将是这样的

 if(UIInterfaceOrientationIsPortrait(orientation)){
 }
 else
 {
 }

确保将单元格子视图保持为自动调整大小的灵活性。

最新更新