How to support auto resizing UITableViewCell with a UILabel in it

…衆ロ難τιáo~ 提交于 2020-01-16 03:08:05

问题


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:


Here is what you need to do:

  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:

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

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

    and also implement delegate method:

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


来源:https://stackoverflow.com/questions/34348555/how-to-support-auto-resizing-uitableviewcell-with-a-uilabel-in-it

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