Prabhu Prabhu - 1 year ago 115
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 {
override func 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 Source

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)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download