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

Bor*_*rdz 9 objective-c uitableview ios autolayout

我有UITableView,每个tableViewCell都是自定义的.在我的customTableViewCell内部是一个UITextView,TextViews框架的引脚或与其superView相同,即tableViewCell. 在此输入图像描述

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

(样本原型)

在此输入图像描述

//这就是我操纵每个细胞高度的方法

- (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.
}
Run Code Online (Sandbox Code Playgroud)

Are*_*lko 7

  1. 请遵循以下答案:链接参考

  2. 向UITextView添加高度约束,并为自定义单元类创建插座.

  3. 使用sizeThatFits:on UITextView获取适合内容的大小,并将此值设置为constant2中描述的约束.执行此操作tableView:heightForRowAtIndexPath:.

一个警告是,如果有很多单元格(数百或数千),那么您可能遇到性能问题.


Kum*_* KL 1

首先获取texts as NSArray 并将其临时分配到 UITextView 中,这样您就可以获得 Cell 的高度:

- (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;
 }
Run Code Online (Sandbox Code Playgroud)

一旦获得了 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


}
Run Code Online (Sandbox Code Playgroud)

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