I am trying to vertically align the text in the UILabel view of my app. The problem is that I want the text to be vertically aligned to the top and the size of the label to
In Swift, JRC’s solution of subclassing UILabel, overriding drawTextInRect and conforming to UIViewContentMode would look like this:
class AlignableUILabel: UILabel {
override func drawText(in rect: CGRect) {
var newRect = CGRect(x: rect.origin.x,y: rect.origin.y,width: rect.width, height: rect.height)
let fittingSize = sizeThatFits(rect.size)
if contentMode == UIViewContentMode.top {
newRect.size.height = min(newRect.size.height, fittingSize.height)
} else if contentMode == UIViewContentMode.bottom {
newRect.origin.y = max(0, newRect.size.height - fittingSize.height)
}
super.drawText(in: newRect)
}
}
Implementing is simply a matter of:
yourLabel.contentMode = UIViewContentMode.top
For me, it worked like a charm.