xcode 通过单元格内 textView 的内容更改单元格高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32652612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:51:26  来源:igfitidea点击:

Change cell height by the content of the textView inside the cell

iosiphonexcodeswiftuitableview

提问by Eliko

I have a Table View called todoTableViewwith cells that created by the user. Each cell has Text View. I want to change the height of the cell by the content of the Text View. This is what I tried:

我有一个todoTableView由用户创建的单元格调用的表视图。每个单元格都有文本视图。我想通过文本视图的内容更改单元格的高度。这是我尝试过的:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: TableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath:indexPath) as! TableViewCell
        cell.bounds.size.height = cell.textView.bounds.size.height

        return cell
    }

回答by Irfan

Bound Your textviewwith cellfrom all sides using marginal constraints.(Leading, Trailing, Top and Bottom constraints)

绑定您textviewcell来自四面八方的使用边际约束。(前置,顶部和底部的约束

enter image description here

在此处输入图片说明

  • Disable textView Scrolling
  • 禁用 textView 滚动

In viewDidLoad()add the following.

viewDidLoad() 中添加以下内容。

tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension

This will make your cell size according to your textview content size.

这将使您的单元格大小根据您的 textview 内容大小。

Have a look at result :

看看结果:

enter image description here

在此处输入图片说明

You don't need to write heightForRowAtIndexPath.

您不需要编写heightForRowAtIndexPath

回答by Elbert Leao

Irfan's answerdidn't work for me.

Irfan 的回答对我不起作用。

It works after I go to Size Inspector and check "Automatic" for "Row Height".

在我转到尺寸检查器并为“行高”选中“自动”后,它就可以工作了。

回答by Peter DeWeese

You should also implement heightForRowAtIndexPath:

您还应该实施heightForRowAtIndexPath

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
{
    return // Calculate your custom row height here.
}