UILabel Basic Tutorial

In this tutorial we will create an app that displays labels. Labels are created using the UILabel class.

Particularly UILabel class implements a read-only text view. You can use this class to draw one or multiple lines of static text, such as those you might use to identify other parts of your user interface. The base UILabel class provides support for both simple and complex styling of the label text. You can also control over aspects of appearance, such as whether the label uses a shadow or draws with a highlight.

public class ViewController extends UIViewController { 
    @Override 
    public void loadView() { 
        UIView mainView = new UIView(); 
        

        setView(mainView); 
    } 
} 

Now lets add some labels to our application. First of all the UILabel Construtor requires a CGRect instance.

CGRect takes four integers that are used in order to initialize a rectangular space on the screen. The first two integers specify the rectangle’s location (the first one is distance from the left and the second distance from top) and the last two specify rectangle’s width and height.

So to put a simple label to the top–left of the screen:

UILabel label = new UILabel(new CGRect(0, 0, 320, 40));

The first two numbers put the label at 0 distance from the left side and 0 distance from the top while the other two make the labels’ rectangle 320 wide and 40 tall.

Now we are ready to add some text to the label. So to do that we will use the setText(String text) method as below:

setText("Hello World!");

Now we only need to add our label to the View and we are done

So finally our code now looks like this:

public class ViewController extends UIViewController {
    @Override
    public void loadView() {
        UIView mainView = new UIView();
        mainView.setBackgroundColor(UIColor.whiteColor());

        UILabel label = new UILabel(new CGRect(0, 0, 320, 40));
        label.setText("Hello World!");

        mainView.addSubview(label);
        setView(mainView);
    }
}

Labels are text elements that are not editable but they are useful as they can respond to events such as clicks.