Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel with custom UIEdgeInsets truncating in UITableViewCell

I have an UITableView with cells that contains an UILabel. The UILabel have a custom UIEdgeInset. I subclassed the UILabel and set the UIEdgeInsets like this:

override func drawText(in rect: CGRect) {
    super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}

override var intrinsicContentSize: CGSize {
    var contentSize = super.intrinsicContentSize
    contentSize.width += leftInset + rightInset
    contentSize.height += topInset + bottomInset
    return contentSize
}

But the label gets truncated sometimes when I have more lines in the UILabel. I've already configured the row height to UITableViewAutomaticDimension and set the estimatedRowHeight. Also the constraints are fine. The problem seems to be when I'm setting the UIEdgeInsets since it works fine if I don't customize it.

Probably I should tell the cell to update the constraints after setting the insets, but I couldn't do this so far.

The constraints where added in storyboard. Bottom, Top, Leading and Trailing are related to the superview (UITableViewCell). All constants set to 0.

In cellForRowAtIndexPath the code is as follows:

let cell = tableView.dequeueReusableCell(withIdentifier: "AnswersCell", for: indexPath) as! AnswerCell  
cell.answerLabel.text = alternatives[indexPath.row]
return cell
like image 396
Lucas Domene Avatar asked Jan 19 '17 22:01

Lucas Domene


1 Answers

Set these two properties of UILable from Attributes inspector section of storyboard

  1. Lines to 0
  2. Line break to word wrap

or you can also set these properties from code.

self.answerLabel.numberOfLines = 0
self.answerLabel.lineBreakMode = .byWordWrapping

and put below code in your UILable's subclass

class CustomLabel: UILabel {

@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 20.0
@IBInspectable var rightInset: CGFloat = 5.0

override func drawText(in rect: CGRect) {
    let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
    super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}

override var intrinsicContentSize: CGSize {
    get {
        var contentSize = super.intrinsicContentSize
        contentSize.height += topInset + bottomInset
        contentSize.width += leftInset + rightInset
        return contentSize
    }
}

}

try this.

Hope it will work for you..

like image 76
Prema Janoti Avatar answered Sep 25 '22 13:09

Prema Janoti