Vertical UILabel Alignment

How can you allign text to the top left in a UILabel? This question took me quite some time, well, as soon as I have searched the web, I found the solution quickly.

The basic solution is to create always a label that has the exact size of the text it contains. With this method, your text starts always at the beggining of your defined label position.

It is quite easy when you know how to do it:

SecondBody = [[UILabel alloc] init];

SecondBody.font = [UIFont systemFontOfSize:15];

// ---------------- MAKING THE LABEL AS HIGH AS THE TEXT INCLUDED ------------------------------

//this is to achieve that the text is always aligned at the top

CGSize maximumSize = CGSizeMake(305, 500); //define the frame (width of label (e.g. 305, plus maximum size possible (here 500 as the text is not going to be bigger than 500)

CGSize secondBodyStringSize = [secondBodyString sizeWithFont:SecondBody.font constrainedToSize:maximumSize

//calculate the height of the string (secondBodyString = Textstring)

//SecondBody.font is the font defined above

//constraining size as defined in maximumSize

//define the linebreakMode

SecondBody.frame = CGRectMake(689, 276, 305, secondBodyStringSize.height); //add the frame to the label

// ---------------- MAKING THE LABEL AS HIGH AS THE TEXT INCLUDED ------------------------------

SecondBody.text = secondBodyString;

[self.view addSubview:SecondBody];

© MR-Apps 2011-2013