如何在自定义UITableViewCell内自动布局动态设置UITextView高度

时间:2013-12-04 07:41:29

标签: ios objective-c uitableview autolayout

我有UITableView,每个tableViewCell都是自定义的。在我的customTableViewCell内部是一个UITextView,TextViews框架的引脚或与其superView相同,即tableViewCell。 enter image description here

我将如何动态设置UITableViewCell高度,该高度与TextViews大小成正比,后者也取决于我从互联网上获得的内容文本。

(样本原型)

enter image description here

//这就是我操纵每个单元格高度的方式

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    // How do I set the height here, whats the best approach for this. with autolayout BTW
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// I initialize every cell here with my ArrayContainer, nothing much to refer here.
}

3 个答案:

答案 0 :(得分:7)

  1. 请按照以下回答:Link reference

  2. 为您的UITextView添加一个高度约束,并为您的自定义单元格类创建一个插座。

  3. sizeThatFits:上使用UITextView获取适合内容的大小,并将此值设置为2中所述约束的constant。在{{1}中执行此操作}}

  4. 有一点需要注意的是,如果有很多单元格(数百或数千),那么您可能会遇到性能问题。

答案 1 :(得分:1)

主要获取texts as NSArray并将其作为临时分配到UITextView中,这样您就可以获得单元格高度:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        CGRect frame;
        //  set the height here, According to the NSArray of text 
        if(textView || section )
        UITextView *tempTxtView = [[UITextView alloc] init];
        tempTxtView.text = // Add the Text of index according to the Section
        // Fit  the  UITextView to the Content 
        frame = tempTxtView.frame;
        frame.size.height = tempTxtView.contentSize.height;
        tempTxtView.frame = frame;
    }    
    return frame.size.height;
 }

获得UITableViewCell高度:然后无需担心这个,对吧?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// I initialize every cell here with my ArrayContainer, nothing much to refer here.

self.textView =  [[UItextView alloc] initWithFrame:CGRectMake(cell.frame.origin.x +20, cell.frame.origin.y +10, cell.frame.size.width - 20, cell.frame.size.height - 20)];

// ....... Do further with the NSArray of Text


}

注意:我没有经过测试,只是一个想法。希望这会对你有所帮助

答案 2 :(得分:0)

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 {
      CGSize titlesize = [TxtValue.text sizeWithFont:[UIFont fontWithName:appdel.strFont size:25.0f] constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];  /// ----- -set width as per your requirement inplace of 300 

      return titlesize.height+10;
 }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{

}