使用UITextView动态设置UITableViewCell的大小

时间:2015-01-13 00:17:34

标签: ios objective-c uitableview uitextview

我在UITableViewCells中有UITextViews。我想要做的是使单元格适合textView 如果单元格包含textView 。我可以为每个单元格创建一个if语句并返回textView的大小(我有一个带有textView的单元格),就像我在下面的代码中所做的那样,但是我确定还有另一种方法这样做。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 && indexPath.row == 0) {
        return myTextview.frame.size.height + 40;
    }
    return 44;
}

我是初学者,所以请不要太苛刻。

2 个答案:

答案 0 :(得分:0)

首先判断单元格是否由UITextView组成。如果是,则根据textview大小给出行高。(但请确保将textview添加到单元格的内容视图中)

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    for (UIView *tempView in  [[tableView cellForRowAtIndexPath:indexPath].contentView subviews])
    {      
        if (tempView isKindOfClass:[UITextView Class])
        {          
            return  tempView.frame.size.height + 40;

             //(or) for dynamic cell height
            //CGSize Size=  [tempView.text boundingRectWithSize:CGSizeMake(200, 1000000)
                                                   options:NSLineBreakByWordWrapping |
                                                  NSStringDrawingUsesLineFragmentOrigin
                                                          attributes:@{
                        NSFontAttributeName :[UIFont fontWithName:@"Helvetica" size:12]
                                                                      }    
                                                        context:nil].size;
             //return Size.height;
         }
     }    
     return 44;
}

答案 1 :(得分:-1)

你总是可以在单元类中执行它,声明一个方法并命名它,例如,

layoutCellByString:(NSString *) stringContent,测量并调整细胞高度

并声明另一个方法在单元类中调用getCellHeight,并返回self.frame.size.height;

并且在heightForRowAtIndexPath中,您可以这样做:

YourCellClassName *cell = (YourCellClassName *)[self tableView:self.tableView cellForRowAtIndexPath:indexPath];

return [cell getCellHeight];

你应该在cellForRowAtIndexPath中调用layoutCellByString才能使这项工作

ps:顺便说一下,为英语池道歉。