How to programmatically add text to a UIView

Steve picture Steve · Jul 9, 2010 · Viewed 60.1k times · Source

I have a UIView that I'd like to add several bits of text to. I have used a UITextView but I think that's overkill as it doesn't need to be editable. I thought about using a UILabel or a UITextField, but I don't see how you tell the superview where to position the UILabel or UITextField within itself. I want the lowest footprint object that will let me put text of a font/color/size of my choosing in my UIView where I want it. Not too much to ask, eh?

Answer

samsam picture samsam · Jul 9, 2010

The simplest approach for you would be:

UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 20)];

[yourLabel setTextColor:[UIColor blackColor]];
[yourLabel setBackgroundColor:[UIColor clearColor]];
[yourLabel setFont:[UIFont fontWithName: @"Trebuchet MS" size: 14.0f]]; 
[yourSuperView addSubview:yourLabel];

Building or populating Views in your code will probably require you to use CGRectMake a lot. As its name says, it creates a rectangle that you can use to set the relative position (relative to the borders of your superview) and size of your UIView-Subclass (in this case a UILabel).

It works like this:

yourLabel.Frame = CGRectMake(x, y, width, height); //x,y,width,height are float values.

x defines the spacing between the left hand border of the superview and the beginning of the subview your about to add, same applies to y but relating to the spacing between top-border of your superview. then width and height are self-explanatory i think.

Hope this gets you on the track.