How can I modify the heightForRowAtIndexPath so that it adjust height to the textview in it,but also keep the minimum height when textview is empty?

▼魔方 西西 提交于 2019-12-25 07:20:01

问题


I have a tableView with static cells inside. One cell contains a map, UITextView and other controls:

This textview has the following constraints:

So far I set up the heightForRowAtIndexPath to the static value for this cell:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
    if indexPath.row == 0 {
        return 311;
    }
}

but then when the text is longer, the textview - instead of growing - contains the text inside and user has to scroll it. Basically it is always 311 in height. I want to change it, so that the whole cell adjust to the textView content.

I tried changing return 311 to return UITableViewAutomaticDimension, but then, when there's no text, the cell shrinks and the controls on the right are not visible.

So my question is - how can I set dynamic height for the cell based on the text inside, but also keep the minimum height of 311?


回答1:


If you are simply displaying the text and not editing it in any way. You should try using a UILabel and the UITableViewAutomaticDeminsions will work as expected with that provided the constraints are correctly added.

What you can do is add a height constraint to the textView and then increase its size based on the size of the string you obtain. Of course you will need to call layoutIfNeeded too! UITableViewAutomaticDimensions should take care of the rest.




回答2:


Add a height constraint to the text view >= the minimum value (what it would be when the cell is 311, then set the cell height to automatic.




回答3:


I don't fully understand your question, but based on what you said maybe this works:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if UITableViewAutomaticDimension > 311 {
            return UITableViewAutomaticDimension
    }
    else {
       return 311
   }
}

I just check if the cell should be bigger than the minimum of 311, and then return either the minimum or something bigger



来源:https://stackoverflow.com/questions/40071611/how-can-i-modify-the-heightforrowatindexpath-so-that-it-adjust-height-to-the-tex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!