Show Menu

Do you have a job opening?

Submit your 30 day Job Listing for FREE

In this tutorial you get to take a look at how to create multiple views and make the touched view follow the users touch.  We also take a look at the simple affair of creating a view in code (programmatically).

First things first, make your way into Xcode, create a new “View-based Application” and for tutorial purposes call it “View Mover”.

Now that XCode has added our Classes for us, lets head to the View Controllers header file (“ViewMoverViewController.h”) to add some instance variables. Add the following code:


@interface HelpViewController : UIViewController {
    CGPoint currentTouch;
    NSMutableArray *viewArray;
    UIView *toMove;
}
- (IBAction)add:(id)sender;
@end

Now let’s go through each of these. The CGPoint is there to store the users latest/current touch, The NSMutableArray is there to store all the views we add (Note that we are not using an NSArray as it doesn’t allow the addition or deletion of objects) and a UIView to store the view that should be moved in the touchesMoved method. We also have an IBAction for the button that will add the views.

Now navigate to the implementation class of the View Controller (“ViewMoverViewController.m”), here it gets slightly more tricky but I am sure you can keep up. First add the following code:


- (void)viewDidLoad {
    viewArray = [[NSMutableArray alloc] init];
}
- (IBAction)add:(id)sender {
    UIView *myAddedView = [[[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)] autorelease];
    myAddedView.backgroundColor = [UIColor redColor];
    [self.view addSubview:myAddedView];
    [viewArray insertObject:myAddedView atIndex:0];
}

First make sure you overwrite the viewDidLoad method that was already there in the file.  Our viewDidLoad method is nice and simple and all the code inside does is initialize our NSMutableArray, “viewArray”. Then to the IBAction, we first create a UIView as a Local Variable and initialize it with a width and height of 100 and x and y as 0. Next we change the background color of the view to red so we can see it, we add the view as a subview to the View the View Controller Controls (to put it simply the view that will be shown) and add the view to our array of views (“viewArray”).

Before we continue programming, let’s nip into Interface Builder. Open up “ViewMoverController.xib”, drag a UIButton in, set it’s title to Add and connect up that IBAction to our button.

Now let’s get back to coding and move on to the touchesBegan method, Add the following code to the same file as before (“ViewMoverViewController.m”):


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint firstTouch = [touch locationInView:self.view];
    for (UIView *view in viewArray) {
        if (CGRectContainsPoint(view.frame, firstTouch)) {
            toMove = view;
        }
    }
}

That will be the hardest code you will find in this tutorial from here on in it’s a breeze.  So, what just happened? Well, we first get any UITouch  from the “touches” NSSet (we don’t need a specific one because in this example app the user will be dragging so there will be only one touch) and then get the location of that touch in the main view as a CGPoint called “firstTouch”. Now let’s look at the next statement in some more detail:


for (UIView *view in viewArray) {

}

Here we loop through the array containing our views and declare a local variable called “view” which will be the current view it’s got to while looping through the array. Then inside that statement we have:


if (CGRectContainsPoint(view.frame, firstTouch)) {
     toMove = view;
}
 

This checks whether “firstTouch”, the location of the users touch,  is within  “view ” .  If it is we set the “toMove” instance variable to the current view it got to while looping through the array.

Now that’s over we finish the app up with the next two methods touchesMoved and touchesEnded both containing the same code. Add the following code:


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    currentTouch = [touch locationInView:self.view];
    toMove.center = currentTouch;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    currentTouch = [touch locationInView:self.view];
    toMove.center = currentTouch;
}

First we get a touch, then the location of that touch and set that to the instance variable “currentTouch” and finally move the center of the view we set as “toMove” in the touchesBegan: method to the location of the users touch .

There you have it! We are now done programming and you can Run your app, add some views and watch them follow your touch like a Dog follows it’s master!

Bonus Line!

For this tutorial I am going to give you a line of code to give the UIView we add a background image rather than a plain background color. Just replace this:


myAddedView.backgroundColor = [UIColor redColor];

With this:


myAddedView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]];

Two things to remember with this; if you want your image to only repeat once make sure the view you add is the same size as the image and most importantly make sure the image (in this case “bg.png”) is in your resources.

There you have it, I hope you enjoyed this tutorial and have fun!

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly


Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.


Written by:

Josh is an indie Mac and iOS Developer with 2 years of experience behind him. You may know him as the developer of Spark for Mac as well as 4Score and 2Code for iOS. He is also a huge Apple lover, a Star Trek fan and active users on both Stack Overflow and Twitter

Comments

comments