Dynamic Height Issue for UITableView Cells (Swift)

前端 未结 25 2530
温柔的废话
温柔的废话 2020-11-28 04:39

Dynamic text of variable length are being injected into tableview cell labels. In order for the tableview cells\' heights to be dynamically sized, I have implemented in

相关标签:
25条回答
  • 2020-11-28 05:08

    SWIFT 3

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 160
    

    AND!!! In storyBoard: You HAVE TO set TOP & BOTTOM constraints for your Label. Nothing else.

    0 讨论(0)
  • 2020-11-28 05:08

    Swift 5 Enjoy

    tablev.rowHeight = 100
    tablev.estimatedRowHeight = UITableView.automaticDimension
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tablev.dequeueReusableCell(withIdentifier: "ConferenceRoomsCell") as! ConferenceRoomsCell
        cell.lblRoomName.numberOfLines = 0
        cell.lblRoomName.lineBreakMode = .byWordWrapping
        cell.lblRoomName.text = arrNameOfRooms[indexPath.row]
        cell.lblRoomName.sizeToFit()
        return cell
    }
    
    0 讨论(0)
  • 2020-11-28 05:11

    I use these

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    
        return 100
    }
    
    0 讨论(0)
  • 2020-11-28 05:11

    You should just set all constraints for TOP, BOTTOM and HEIGHT for each object on cell view/views and remove exists middle Y position if have. Because where you didn't this, puts artifacts on another views.

    0 讨论(0)
  • 2020-11-28 05:11

    I had also got this issue initially, I had resolved my issue from this code try avoiding the use of self.tableView.reloadData() instead of this code for dynamic height

    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
    
    0 讨论(0)
  • 2020-11-28 05:12

    For Swift 4.2

    @IBOutlet weak var tableVw: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Set self as tableView delegate
        tableVw.delegate = self
    
        tableVw.rowHeight = UITableView.automaticDimension
        tableVw.estimatedRowHeight = UITableView.automaticDimension
    }
    
    // UITableViewDelegate Method 
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    
        return UITableView.automaticDimension
    }
    

    Happy Coding :)

    0 讨论(0)
提交回复
热议问题