Posts Tagged ‘Code’

Creating programmatically a label (UILabel)

May 8th, 2009

UILabel allows you to display a single line text, most of us think so. In fact it can be used to display multiple lines as well.

To create an UILabel programmaticaly, code:

	UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
To display a text within UILabel use:
	myLabel.text = @"Lorem...";

And of course to add UILabel to your view:

	[self.view addSubview:myLabel];

By default UILabel has a white background, you can remove the background or change the color easily:

	myLabel.backgroundColor = [UIColor clearColor]; // [UIColor brownColor];

Setting the font:

	myLabel.font = [UIFont fontWithName:@"Zapfino" size: 14.0];

You can easily get a list of available fonts and the preview of them, using the free application Fonts! by AppEngines. UILabel can display text in different color then black and shadows as well:

	myLabel.shadowColor = [UIColor grayColor];
	myLabel.shadowOffset = CGSizeMake(1,1);
	myLabel.textColor = [UIColor blueColor];

Best effect you will obtain by setting a color using RGB while setting the alpha half transparent. shadowOffset gives you the ability to set the shadow’s angle.

By default text is horizontally aligned to the left, you can set it either to the right or to the center.

	myLabel.textAlignment = UITextAlignmentRight; // UITextAlignmentCenter, UITextAlignmentLeft

Text wrapping

As I told you, UILabel can display multiple lines of text, and to achieve it you need to set two properties lineBreakMode and numberOfLines:

	myLabel.lineBreakMode = UILineBreakModeWordWrap;
	myLabel.numberOfLines = 2; // 2 lines ; 0 - dynamical number of lines
	myLabel.text = @"Lorem ipsum dolor sit\namet...";

That’s all about UILabel. More can be found in UILabel Class Reference in documentation.