Friday, 29 April 2016

Pan Gesture Recognizer



For basic overview of Gesture Recognizer Click here
We will continue here with Pan Gesture Recognizer. Pan Gesture Recognizer allow to drag view around the screen.In this part, except for implementing the necessary code that will enable our app to support the pan gesture.
The pan gesture is actually a drag gesture. It’s used when it’s needed to drag views from one point to another.

First create a view
UIView *panView =  [[UIView alloc]initWithFrame:CGRectMake(0, 0, 60, 60)];
panView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:panView];

Defining Callback method for Gesture Recognizer

-(void) handlepanGesture:(UIPanGestureRecognizer *)panGesture{
    CGPoint touchPoint = [panGesture locationInView:self.view];
    panView.center = touchPoint;
}


Now run the app and check.
You can drag 'Pan View' around main View.

The approach I presented above is simple for the sake of the tutorial. In a real application, you might want to enrich the movement of the view by adding acceleration or deceleration when you start or stop dragging, or anything else you need. It’s up to you to apply the proper logic in the action method you implement.

You can find points per second the dragged view travels in both the horizontal and vertical axis while dragging by method velocityInView: .
Go to Callback method and add following codes

//find velocity
       CGPoint velocity = [panGesture velocityInView:self.view];
       NSLog(@"Horizontal Velocity: %.2f points/sec",velocity.x);
       NSLog(@"Vertical Velocity: %.2f points/sec",velocity.y);

Now run the app again and drag panView.
you can check horizontal  and vertical velocity on Console Area.

</script>

Friday, 22 April 2016

Swipe Gesture

In this tutorial i am going to show how to use UISwipeGestureRecognizer in the App.
You can find basic overview of Gesture Recognizer in the Previous tutorials.Click here
By using UISwipeGestureRecognizer we can swipe a view in any of the following directions:
1)  Left
2) Right
3) Top
4) Bottom

UISwipeGestureRecognizer class provide a method that allow to specify direction for swipe, if none is set, than right direction used by default.
A Swipe Gesture Recognizer object can monitor and trigger action for specified direction only.
Means, if we want a view in application that support swiping in more than one direction than need to add more than one Swipe Gesture Recognizer to view or you can change direction of Swipe Gesture Recognizer to swipe a view in different direction with one Swipe Gesture.

In this example i will use one Swipe Gesture for swiping a view in left and right both direction.

I assume you know how to create New project, i am not going to show here, mainly i will focus on how to how to use Swipe Gesture in a application.

Firstly i am creating a view.
UIView *swipeView =  [[UIView alloc] initWithFrame:self.view.bounds];
swipeView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:swipeView];


Now i am going to define Callback method for Gesture Recognizer
-(void) handleSwipeGesture:(UISwipeGestureRecognizer *)swipeGesture{
         NSLog(@"Swipe Gesture Detected");
}


Adding Gesture to view
UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGestureRecognizer:)];
swipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
[swipeView addGestureRecognizer:swipeGesture];


Its enough, if you run the app, can see a orange view above the main view. if you swipe orange view to right, Gesture Recognizer triggered and send a message to  Callback method.
for confirmation you can check and console, you can see "Swipe Gesture Detected" printed on console.
Now  i am going to swipe orange view from left to right (if orange view origin.x is 0) and from right to left(if orange view origin.x is greater than 0).
Go to 'handleSwipeGesture:' and add following code

-(void) handleSwipeGesture:(UISwipeGestureRecognizer *)swipeGesture{
         UISwipeGestureRecognizerDirection direction = swipeGesture.direction;
//give specified          Direction
         UIView *swipeView = swipeGesture.view; //return instance of specified view
         //Check Specified Direction
         if (direction==UISwipeGestureRecognizerDirectionRight) {
                [UIView animateWithDuration:.6 animations:^{
                swipeView.frame = CGRectMake(300, swipeView.frame.origin.y, swipeView.frame.size.width,    swipeView.frame.size.height);
              swipeGesture.direction = UISwipeGestureRecognizerDirectionLeft; //Change direction
             }];
      
       }
     else if (direction==UISwipeGestureRecognizerDirectionLeft) {
            [UIView animateWithDuration:.6 animations:^{
                 swipeView.frame = CGRectMake(0, swipeView.frame.origin.y, swipeView.frame.size.width,  swipeView.frame.size.height);
                 swipeGesture.direction = UISwipeGestureRecognizerDirectionRight; //Change direction
         }];
      
    }
   else{
            NSLog(@"Unknown Direction");
   }
}



Now run app again and check.
After swipe  toward Right, Orange view slide to right, and again swipe toward Left Orange View slide left.

Note:  If you swipe toward Right Orange view slide to right and again you swipe toward right its won't work, because we changed direction from Right to Left.

Friday, 8 April 2016

Gesture Recognition


Overview
In iOS 3.0, Apple introduce new UIGestureRecognizer Class! These provide a default implementation of detecting common gestures such as taps, pinches, rotations, swipes, pans, and long presses.
Gesture recognizers convert low-level event handling code into higher-level actions. They are objects that  attach to a view, which allows the view to respond to actions the way a control does. If they recognize their assigned gesture, they send an action message to a target object. The target object is typically the view’s view controller, which responds to the gesture.

A view can have with multiple Gesture Recognitions but a  Gesture Recognizer can't associate with multiple views.

Gesture Recognizer classes of the UIKit framework
Tap (any number of taps) = UITapGestureRecognizer
Pinch  (for zooming)        = UIPinchGestureRecognizer
Pan or Drag                      = UIPanGestureRecognizer
Swipe (any direction)      =  UISwipeGestureRecognizer
Rotating                           =  UIrotationGestureRecognizer
Long Press                       =  UILongPressGestureRecognizer
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

UITapGestureRecognizer:

UITapGestureRecognizer is sub class of UIGestureRecognizer that look for single and multiple taps on associated view.
Adding UITapGestureRecognizer to a view.
1) Creating a Gesture Recognition: You can create a Gesture Recognition by specifying a callback method  so the Gesture Recognition send you update when gesture starts, changes, or ends.
2)Add Gesture Recognition to View : Each gesture is associated with one view.When a touch occurs within the bounds of that view, the gesture recognizer see if it matches the type of touch it’s looking for, and if a match is found it will notify the callback method.

Example:
Adding a Tap Gesture Recognizer to a View:

CallBack method for Gesture Recognizer:
-(void) handleTapGestureRecognizer:(id) sender{
       NSLog("Tap Gesture Occurred");
}

Adding Gesture to view
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGestureRecognizer:)];
tapGesture.numberOfTapsRequired = 2;    //Default is 1.
[view addGestureRecognizer:tapGesture];

Note: userInteractionEnabled is always "YES" for specified view.

In the same way you can use rest of Gesture Recognizers.













Friday, 1 April 2016

Singleton Class


One of the most used design patterns for developing  iOS application. It's a way to share data between different part of code without having to pass the data around manually.

Singleton is a design pattern that restricts the instantiate of a class to one object. A singleton class returns the same instance no matter how many times an application requests.

Implementation
Create a sub class of NSObject(named: DatabaseHandler)

#import <Foundation/Foundation.h>

@interface DatabaseHandler : NSObject 
     
     +(DatabaseHandler *) sharedInstance
@end


#import "DatabaseHandler.h"

static DatabaseHandler *sharedInstance;
@implementation DatabaseHandler

#pragma mark -
+(DatabaseHandler *) sharedInstance{
   
    @synchronized(self){
       
        if (!sharedInstance) {
            sharedInstance = [[DatabaseHandler alloc] init];
        }
    }
    return sharedInstance;
}

@end

We can declare properties and methods in Singleton class as same like other classes.

 code:

#import <Foundation/Foundation.h>

@interface DatabaseHandler : NSObject 
        @property (nonatomic, strong) NSString *stringValue;
        @property (nonatomic, assign) BOOL check;

       
        +(DatabaseHandler *) sharedInstance
        -(void) initialization;
        -(void) fetchResult;
@end

 goto DatabaseHandler.m

#import "DatabaseHandler.h"

static DatabaseHandler *sharedInstance;
@implementation DatabaseHandler

#pragma mark -
+(DatabaseHandler *) sharedInstance{
   
    @synchronized(self){
       
        if (!sharedInstance) {
            sharedInstance = [[DatabaseHandler alloc] init];
        }
    }
    return sharedInstance;
}


//Initialization at time of creation object(if want to do any operation or set default value, its totally optional)
-(id) init{
    [self initialization];
}
 -(void) initialization{
     check = NO;
     stringValue = @"defaultValue";
}

-(void) fetchResult{
      NSLog(@"Fetch Call");
}
@end


Access to Singleton class methods and properties from outside(another classes)

1)import singleton class.

2) create object for singleton class
DatabaseHandler *databaseHandler = [DatabaseHandler sharedInstance];

3) Set value to property declared in Singleton class
databaseHandler.stringValue = @"New Value";
in the same way
databaseHandler.check = YES;

4) Get value from property declared in Singleton class
NSString *value = databaseHandler.stringValue;
BOOL check = databaseHandler.check;

5)Call methods declared in Singleton class
[databaseHandler fetchResult];