如何在使用自动布局的自定义UITableViewCell中动态设置UITextView的高度

9
我有一个UITableView,每个tableViewCell都是自定义的。在我的自定义TableViewCell中有一个UITextView,TextView的框架被固定或与其父视图(即tableViewCell)相同。 如何动态设置UITableViewCell的高度,使其与来自互联网的内容文本相关的TextView大小成比例地变化。 (样品原型) //这是我如何操作每个单元格高度
- (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个回答

7
  1. 请跟随这个答案: 链接参考

  2. 为你的UITextView添加高度约束并创建一个指向自定义单元格类的outlet。

  3. 使用UITextView上的sizeThatFits:方法获取适合内容的大小,并将此值设置为在步骤2中描述的约束的constant。在tableView:heightForRowAtIndexPath:中执行此操作。

需要注意的是,如果有大量单元格(数百或数千个),则可能会遇到性能问题。


@Spail:你能检查一下从调用sizeThatFits:返回的正确尺寸吗? - Arek Holko
是的,返回的尺寸有点奇怪。它的宽度比应该的要大。你能把你的代码发出来吗? - Spail
没事了,我忘记加上+1来计算单元格分隔符的高度。现在看起来好像可以了。谢谢。 - Spail

1
主要是将文本作为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


}

注意:我没有进行测试,这只是一个想法。希望这能帮到你。


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 
{

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接