Dec 7, 2009

Touch the code

XcodeImage via Wikipedia
In this first article I want to give you some information on how to manage touch events and use them to move an object into the main window.

Open Xcode and create a new window-based application's project. Give it a name (I chose TestTouch).
The wizard will create the application's delegate object positioned into the Classes group.

Now we have to add a view over the main window and create a class associated to it that will receive the touch events and will manage them.

Go to File menu and choose "New File"; from the Cocoa Touch Class choose Object-C class and from the Subclass combo choose UIView, then press Next and give a name to the new class. I named it TouchView.

Now in the TouchView.h add an IBOutlet as follow:

IBOutlet UIView *followerView;

Now go to the TouchView.m file and insert the code that will be used to intercepts the touches and manage them:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
}

Leave empty the touchesBegan and touchesMoved (we will use them in the next lesson). Inside the method touchesEnded we have to put the code to catch the touch position and move consequently the 'followerView' view we defined previously.
First we have to get the touch object:

UITouch *touch = [touches anyObject];

and then extract the position related to the screen:

CGPoint pos = [touch locationInView:self];

and then set the new position to the follower view:

[followerView setCenter:pos];

To complete the exercise we have to open the MainWindow.xib. By double clicking on it the InterfaceBuilder will open.
Add a UIView widget over the Window and in the Identity tab as Class choose the TouchView we created before.

Add another UIView widget over the view just added and make it to be a small square (With = height = 37 for example).
Give the two UIView different background colors (I used black for the main view and red for the small one).
The last step is to connect the IBOutlets we defined into the TouchView with the small red view. Do it from the InterfaceBuilder.
Press "Build and Go" in the Xcode and enjoy with the small square that will follow your touches on the device ;)
You can find here the Xcode project with the source code.

Reblog this post [with Zemanta]

No comments:

Post a Comment