Skip to content

Instantly share code, notes, and snippets.

@anirudhamahale
Last active April 24, 2017 11:56
Show Gist options
  • Save anirudhamahale/3e5c3ecf33d7fd17248187f36769f2a0 to your computer and use it in GitHub Desktop.
Save anirudhamahale/3e5c3ecf33d7fd17248187f36769f2a0 to your computer and use it in GitHub Desktop.
Top left UIlabel text
import UIKit
@IBDesignable class TopAlignedLabel: UILabel {
override func drawText(in rect: CGRect) {
if let stringText = text {
let stringTextAsNSString = stringText as NSString
let labelStringSize = stringTextAsNSString.boundingRect(with: CGSize(width: self.frame.width,height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil).size
super.drawText(in: CGRect(x:0,y: 0,width: self.frame.width, height:ceil(labelStringSize.height)))
} else {
super.drawText(in: rect)
}
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
layer.borderWidth = 1
layer.borderColor = UIColor.black.cgColor
}
}
@anirudhamahale
Copy link
Author

anirudhamahale commented Apr 22, 2017

txzmg
This is what it achieves.
The answer has been taken from this link

Thanks to Daniel Galasko for the answer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment