How to programmatically add text to a UIView How to programmatically add text to a UIView xcode xcode

How to programmatically add text to a UIView


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.


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.


For Swift:

    let yourLabel = UILabel(frame: CGRectMake(100, 100, 100, 100))    yourLabel.textColor = UIColor.whiteColor()    yourLabel.backgroundColor = UIColor.blackColor()    yourLabel.text = "mylabel text"    yoursuperview.addSubview(yourLabel)