How to use accelerometer in iPhone

How to use accelerometer in iPhone

 

In our last post we discussed how to make the keyboard disappear in our App to make it more  user-friendly. Later in the tutorial we saw that our App was not adjusting itself to the rotations of the iPhone i.e iPhone rotated left or rotated right like the standard applications. So today we are going to discuss how to do this.

Accelerometer in iPhone :-

Apple provides Accelerometer in iPhone which allows the device to know when it is tilted on its side or shaken. The developers can make use of this and can generate different events to make the app respond to these orientation changes.

So now lets see how to use Accelerometer in our “basic” app. So after the second tutorial, our app looked somewhat like this

iPhone Application Development

Now if we try to change the orientation by just going to the “Hardware” in the top menu of “iPhone Simulator” and selecting “Rotate Left” from it, we see that our app didn’t adjust itself to the change in orientation.

iphone

 

iphone

So now lets get started :-

1.)  Open the “basicViewController.m” file and add the following code

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
   return YES;
   }

This enables our App to respond to the rotations in the orientation.

Now we need our Interface elements i.e the button and textfield to adjust its size to the change in orientation.

 

2.) Making button and textfield to adjust its size to the change in orientation

a.) Click on the “basicviewController.xib” file to open the Interface Builder. In the Size Inspector, we can view the size and orientation of our interface elements.

b.) Select the textfield and make the AutoSizing attribute look like

iPhone Application Tutorials

c.) Similarly select the button and make its AutoSizing attribute look like

iPhone Application Development

d.) Save it and “Build and Go”.

e.) Now again try to rotate the iPhone Simulator, you will see that the interface adjusts itself to the change in orientation.

Finally here is what our app looks like.

iphone