UITableView dynamic cell heights only correct after some scrolling

后端 未结 24 1247
误落风尘
误落风尘 2020-11-29 16:41

I have a UITableView with a custom UITableViewCell defined in a storyboard using auto layout. The cell has several multiline UILabels.

相关标签:
24条回答
  • 2020-11-29 17:18

    I tried all of the solutions in this page but unchecking use size classes then checking it again solved my problem.

    Edit: Unchecking size classes causes a lot of problems on storyboard so I tried another solution. I populated my table view in my view controller's viewDidLoad and viewWillAppear methods. This solved my problem.

    0 讨论(0)
  • 2020-11-29 17:18

    The problem is that the initial cells load before we have a valid row height. The workaround is to force a table reload when the view appears.

    - (void)viewDidAppear:(BOOL)animated
    {
      [super viewDidAppear:animated];
      [self.tableView reloadData];
    }
    
    0 讨论(0)
  • 2020-11-29 17:20

    calling cell.layoutIfNeeded() inside cellForRowAt worked for me on ios 10 and ios 11, but not on ios 9.

    to get this work on ios 9 also, I call cell.layoutSubviews() and it did the trick.

    0 讨论(0)
  • 2020-11-29 17:20

    I have the issue with resizing label so I nee just to do
    chatTextLabel.text = chatMessage.message chatTextLabel?.updateConstraints() after setting up the text

    // full code

    func setContent() {
        chatTextLabel.text = chatMessage.message
        chatTextLabel?.updateConstraints()
    
        let labelTextWidth = (chatTextLabel?.intrinsicContentSize().width) ?? 0
        let labelTextHeight = chatTextLabel?.intrinsicContentSize().height
    
        guard labelTextWidth < originWidth && labelTextHeight <= singleLineRowheight else {
          trailingConstraint?.constant = trailingConstant
          return
        }
        trailingConstraint?.constant = trailingConstant + (originWidth - labelTextWidth)
    
      }
    
    0 讨论(0)
  • 2020-11-29 17:21

    In my case, I was updating in other cycle. So tableViewCell height was updated after labelText was set. I deleted async block.

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = tableView.dequeueReusableCell(withIdentifier:Identifier, for: indexPath) 
         // Check your cycle if update cycle is same or not
         // DispatchQueue.main.async {
            cell.label.text = nil
         // }
    }
    
    0 讨论(0)
  • 2020-11-29 17:25

    For me none of these approaches worked, but I discovered that the label had an explicit Preferred Width set in Interface Builder. Removing that (unchecking "Explicit") and then using UITableViewAutomaticDimension worked as expected.

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