Dynamically calculating textWidth in tableCells become wrong after scrollToRowAtIndexPath

时间:2016-05-17 11:10:14

标签: ios swift uitableview

When I tried to scroll table to the bottom using this way

  let ip = NSIndexPath(forItem: array.count - 1, inSection: 0)
  chatTableView.scrollToRowAtIndexPath(ip, atScrollPosition: .Top, animated: true)

Cell width calculating:

private var leadingConstant: CGFloat = 30

@IBOutlet weak var leadingConstraint: NSLayoutConstraint! {
   didSet {
      leadingConstant = leadingConstraint!.constant
      }
   }

   private func resizeCell() {
     let labelTextWidth = chatTextLabel?.intrinsicContentSize().width
        guard labelTextWidth < lWidth else {
          return
        }
        leadingConstraint?.constant = leadingConstant + lWidth -  labelTextWidth!
   }

I will get the wrong calculation of textWidth in cells

enter image description here

1 个答案:

答案 0 :(得分:0)

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

var chatMessage: ChatMessage! {
    didSet {
      setContent()
    }
}

func setContent() {
    chatTextLabel.text = chatMessage.message
    chatTextLabel?.updateConstraints()  // here

    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)

  }