Pages

How to Programmatically Design UILabel in Swift

Drawing Labels on View Controller Programmatically :

Drawing UI by Dragging & Dropping UI Components is pretty much easy task to do but Drawing UI only through shear coding is a task that will take a lot out of you...But it is quiet an easy task when you pay attention to it && I bet you will completely forget about Dragging && Dropping objects from the Inbuilt Library the XCode is providing.

Here is an Example of how you draw a label on the screen programmatically:


1. The very first thing you do is to create a Xcode project by usual setting of Single View Application & selecting the language Swift.

2. Now add following bit of code to your viewDidLoad() method of ViewController.swift class

             //Mark:- 2nd label ----->

        var label = UILabel()               //declaring variable of label type
        label.frame = CGRectMake(50, 50, 200, 30)   //setting frame
        label.backgroundColor = UIColor.brownColor()//setting backgroundColor
        label.textColor = UIColor.whiteColor()      //setting text color
        label.textAlignment = NSTextAlignment.Left //setting alignment of text to left in label
        label.text = "My First Label"               //writing text on the label
        self.view.addSubview(label)                 //adding subView
        
        //Mark:- 2nd label ----->
        
        var label2 = UILabel()               //declaring variable of label type
        label2.frame = CGRectMake(50, 100, 250, 40//setting frame
        label2.backgroundColor = UIColor.greenColor()//setting backgroundColor
        label2.textColor = UIColor.purpleColor()     //setting text color
        label2.textAlignment = NSTextAlignment.Right //setting alignment of text to right in label
        label2.text = "My Second Label"              //writing text on the label
        self.view.addSubview(label2)                 //adding subView


It will look something like..



Both of these labels have their own properties in 1st label test is left aligned & size and width are different && in second label text is right aligned and heights & width are different from 1st label. Comments in the code well described these properties.

There are a lot of properties you can play with. Try all of them Out.


Well guess what..That's all. Now Run Your Project & you will see something like....



Well you can see the interface is good for nothing now but you can make it pretty much impressive by designing it in your own ways.

The first label here is the result of code mark with (//Mark:- 1st label -----> ) and
The second label here is the result of code mark with (//Mark:- 2nd label -----> ).

Now enjoy the coding guys..I hope this project was of good help to you.



No comments:

Post a Comment