Pages

Reacting to the Orientation change of the device

Well guys as you know that you can apply constraints to any object in the storyboard by applying auto layout constraints.Whenever the orientation of the device changes if you are designing interface with storyboard it is good as butter, but when you are so fond of doing everything programmatically you will found that it is quite difficult to react according to the change of the orientation of the device. Well now I will show you a way out of many to tackle to this kind of problem. Well all you will be using is a function named as "didRotateFromInterfaceOrientation()". It takes an argument of "UIInterfaceOrientation" type. This function will get executed whenever user's device orientation will get changed. This function is defined in View Controller super class && any class that wants to use it should "override" this function for performing any additional task.
Lat us understand it with an example as usual creating a label && whenever the orientation of the devices changes the label will be redrawn but one task that you need to do is to remove the existing label from superView. Now go ahead && create a  xCode project && in the viewDidLoad() function of the ViewController.Swift file.


    var label = UILabel()
    override func viewDidLoad() {
        super.viewDidLoad()        
        label.frame = CGRectMake(20, 50, view.bounds.size.width - 40, 30)
        label.backgroundColor = UIColor.greenColor()
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Left
        view.addSubview(label)
    }

All this code is doing is just drawing a label whenever the view will be loaded. And now here comes the real magical function which will first remove the label from super view && then redraw the label again according to the changed orientation of the device. Here is the function:


override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation)               
    {
                //remove the existing drawn label from super view
        label.removeFromSuperview()
                // redrawing the label
        label.frame = CGRectMake(20, 50, view.bounds.size.width - 40, 30)
        label.backgroundColor = UIColor.greenColor()
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Left
        view.addSubview(label)

    }

This is the main function which will redraw the label according to orientation changes. Well there are many other ways to do so another way is by applying the constraints programmatically. But this was the simplest for novice users, isn't it. Now try and change the orientation of your simulator && you will see the effect of this function.

No comments:

Post a Comment