I have been attempting to get insets working with a UILabel by using this subclassed method:
@IBDesignable class TextLabelWithInsets: UILabel {
@IBInspectable var topInset: CGFloat = 0.0
@IBInspectable var leftInset: CGFloat = 0.0
@IBInspectable var bottomInset: CGFloat = 0.0
@IBInspectable var rightInset: CGFloat = 0.0
var insets: UIEdgeInsets {
get {
return UIEdgeInsetsMake(topInset, leftInset, bottomInset, rightInset)
}
set {
topInset = newValue.top
leftInset = newValue.left
bottomInset = newValue.bottom
rightInset = newValue.right
}
}
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
print("Content Size: " + String(describing: contentSize))
return contentSize
}
}
The problem is that this only works for smaller blocks of text. It seems as if as soon as the text gets long enough, the last line is cut off.
Any ideas how this can be fixed? Adding extra pixels to the height works but makes smaller ones look dumb. I dont know what the problem is here, the code makes sense in my head.
Here is the rest in case this helps:
func commonInit() {
oppositeSideEdgeSpacing = screen.size.width/4
textLabel = TextLabelWithInsets(frame: .zero)
textLabel.layer.cornerRadius = bubbleCornerRadius
textLabel.clipsToBounds = true
textLabel.topInset = bubbleTopInsetSpacing
textLabel.bottomInset = bubbleBottomInsetSpacing
textLabel.leftInset = bubbleLeftInsetSpacing
textLabel.rightInset = bubbleRightInsetSpacing
textLabel.numberOfLines = 0
textLabel.translatesAutoresizingMaskIntoConstraints = false
textLabel.textAlignment = .left
textLabel.backgroundColor = UIColor(hexString: "CDDCE0") // TODO: Fix this
addSubview(textLabel)
if !isMessageFromCurrentUser {
textLabel.topAnchor.constraint(equalTo: topAnchor, constant: bubbleEdgeSpacing).set(active: true)
textLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: bubbleEdgeSpacing).set(active: true)
textLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -oppositeSideEdgeSpacing).set(active: true)
textLabel.bottomAnchor.constraint(equalTo: bottomAnchor).set(active: true)
}
}
