如何支持使用UILabel自动调整UITableViewCell的大小

wxc*_*der 1 uitableview ios swift swift2

我试图弄清楚如何获得包含uitextview的tableview单元格的正确高度,以便显示uitextview中的所有内容.textview不可编辑且不可滚动,这意味着uitextview的字符串是已知的.我尝试简单地返回故事板中的tableview单元格的高度,heightForRowAtIndexPath但是如果内容太大则会切断内容.我也尝试计算textView的高度,heightForRowAtIndexPath但它在运行时抛出一个错误:

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

Shr*_*ada 6

这是你需要做的:

  1. 需要在单元格中使用自动布局,并为UILabel设置适当的约束.由于我们想要调整UILabel的大小以适应它的文本集,我们将行数值设置为0.然后将前导,尾随,底部和顶部约束设置为UILabel.请看这里的截图:

    行为0 在此输入图像描述

  2. 在Table View控制器> viewDidLoad中调用以下两行:

      tableView.estimatedRowHeight = 50.0  //Give an approximation here
      tableView.rowHeight = UITableViewAutomaticDimension
    
    Run Code Online (Sandbox Code Playgroud)

    并实现委托方法:

     override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
        return UITableViewAutomaticDimension
      }
    
    Run Code Online (Sandbox Code Playgroud)