我一直试图通过使用这个子类方法来获取使用UILabel的插图:
@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
}
}
问题是这只适用于较小的文本块。似乎只要文本足够长,最后一行就会被切断。
任何想法如何解决这个问题?在高度上添加额外的像素会起作用,但会使较小的像素看起来很笨我不知道这里的问题是什么,代码在我脑海中是有意义的。
以下是其他有用的情况:
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)
}
}