Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically add text to a UIView

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?

like image 357
Steve Avatar asked Jul 09 '10 04:07

Steve


2 Answers

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.

like image 60
samsam Avatar answered Sep 20 '22 09:09

samsam


Instead of finding a way to tell the view where to position the UILabel, you can tell the UILabel where to position itself in the view by using "center".

E.g.

myLabel.center = CGPointMake(0.0, 0.0); 

Hope you'll be able to use UILabel, for me it's the basic form of a flexible non editable text.

like image 43
Manny Avatar answered Sep 17 '22 09:09

Manny