如何通过其中的UILabel支持自动调整UITableViewCell的大小 [英] How to support auto resizing UITableViewCell with a UILabel in it

查看:86
本文介绍了如何通过其中的UILabel支持自动调整UITableViewCell的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何为包含uitextview的tableview单元获取正确的高度,以便显示uitextview中的所有内容. textview是不可编辑且不可滚动的,这意味着uitextview的字符串是已知的.我尝试简单地返回heightForRowAtIndexPath中情节提要中的tableview单元格的高度,但是如果内容太大,则会切断内容.我还尝试计算heightForRowAtIndexPath中textView的高度,但在运行时会引发错误:

I am trying to figure out how get the correct height for my tableview cell that contains a uitextview so that all the content in the uitextview will be display. The textview is not editable and not scrollable, which means that the string for the uitextview is known. I tried simply returning the height of the tableview cell that is in the storyboard in heightForRowAtIndexPath but that cuts off the content if it is too large. I also tried calculating the height for the textView in heightForRowAtIndexPath but it throws an error at runtime:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let cellInfo = UserCellsArray[indexPath.section]
        switch cellInfo {
        case .userInfo: return 104
        case .ubio:
            let cell = tableView.dequeueReusableCellWithIdentifier(cellInfo.description, forIndexPath: indexPath) as! UserProfileTableViewCell //error
            let oldHeight = cell.userBio.frame.size.height
            cell.userBio.text = self.bio
            var bodyframe = cell.userBio.frame
            bodyframe.size = cell.userBio.contentSize
            let newHeight = cell.userBio.contentSize.height
            return tableView.rowHeight - oldHeight + newHeight
        }
    } 

推荐答案

这是您需要做的:

  1. 需要在单元格中使用自动布局,并为UILabel设置适当的约束.由于我们要调整UILabel的大小以适合其设置的文本,因此我们将行数值设置为0.然后将UILabel的前,后,下和上约束设置为.请在此处查看屏幕截图:

  1. Need to use auto layout in your cell and set up appropriate constraints for UILabel. Since we want to resize the UILabel to fit the text set to it, we will set the number of lines value to 0. And then set the leading, trailing, bottom and top constraints to the UILabel. Please see screenshots here:

在您的Table View控制器中> viewDidLoad调用这两行:

In your Table View controller > viewDidLoad call these two lines:

  tableView.estimatedRowHeight = 50.0  //Give an approximation here
  tableView.rowHeight = UITableViewAutomaticDimension

并实现委托方法:

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

这篇关于如何通过其中的UILabel支持自动调整UITableViewCell的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆