Prabhu Prabhu - 3 months ago 16
iOS Question

How to create a bottom aligned label in Swift?

There are several examples on how to create a Top Aligned label in Swift. Here is on that works for me:

@IBDesignable class TopAlignedLabel: UILabel {
override func drawTextInRect(rect: CGRect) {
if let stringText = text {
let stringTextAsNSString = stringText as NSString
var labelStringSize = stringTextAsNSString.boundingRectWithSize(CGSizeMake(CGRectGetWidth(self.frame), CGFloat.max),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil).size
super.drawTextInRect(CGRectMake(0, 0, CGRectGetWidth(self.frame), ceil(labelStringSize.height)))
} else {
super.drawTextInRect(rect)
}
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
layer.borderWidth = 1
layer.borderColor = UIColor.blackColor().CGColor
}
}


I am trying to modify this to create a bottom aligned label, but struggling to find the right thing to change. Any help is appreciated!

Answer

Change this line:

super.drawTextInRect(CGRectMake(0, 0, CGRectGetWidth(self.frame), ceil(labelStringSize.height)))

Into this:

super.drawTextInRect(CGRectMake(0, rect.size.height - labelStringSize.height, CGRectGetWidth(self.frame), ceil(labelStringSize.height)))
Comments