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];

Friday, 18 March 2016

View Animation

A constraint defines a relationship between two user interface objects that must be satisfied by the constraint-based layout system.

For presenting a view with constraint if little bit different.
We can use frame property for animating a view object.
We can change size and origin by setting new value inside animation block.

Here an example for animating 2 UIView object with constraint.

1) Add one UIView object on XIB file.
set following constraint
  a) Leading constraint(Margin from left)  = 0
  b)Tailing constraint(margin from right) = 0
  c) Top constraint(from super view) = 0
  d) Height constraint = 0

2) Add one more UIView object.(for differentiate set different-2 background color)
 set following constraint on newly added UIView object
  a) Leading constraint(Margin from left)  = 0
  b)Tailing constraint(margin from right) = 0
  c) Top constraint (From first UIView object not from super view)= 0
  d)Bottom constraint = 0

Now, define a IBOutlet property for NSLayoutConstraint
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *topHeightConstraint;

On XIB connect topHeightConstraint with Height Constraint of Top or first UIView object.






Add a button for animating both view.
Here action of button

-(void) animationButtonAction:(UIBarButtonItem *)barButton{
    if (self.topHeightConstraint.constant == 0) {
        NSLog(@"Increase height");
        self.topHeightConstraint.constant = 300;
    }
    else{
        NSLog(@"Decrease height");
        self.topHeightConstraint.constant = 0;
    }
    [UIView animateWithDuration:1 animations:^{
        [self.view layoutIfNeeded];
    }];
}


Now, Its all set for animating UIView objects with NSLayoutConstraint.=

Friday, 11 March 2016

CAShapeLayer

CAShapeLayer is a specialized subclass of CALayer that draws itself using the shape you define via the path property. path is an instance of CGPath. We could leverage the convenient UIBezierPath APIs to create a path, and then retrieve the CGPath from it. Besides all the animatable properties inherited from CALayer, there are other animatable properties that let you control attributes such as fill color, stroke color, line thickness, etc.


Set rounded corner of a 'UIView' using "CAShapeLayer" 

//First create a instance of UIView
UIView *rectangleView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 300, 300)];

//set background color of UIView
rectangleView.backgroundColor = [UIColor redColor];

//Add subview to main view
[self.view addSubview:rectangleView];

//Create a instance of CAShapeLayer
CAShapeLayer *shapeLayer = [CAShapeLayer layer];

//set path for CAShapeLayer property's 'path'
UIBezierPath *shapePath =[UIBezierPath bezierPathWithRoundedRect:rectangleView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(10, 10)];

//set CAShapeLayer Path
shapeLayer.path = shapePath.CGPath;

//Add CAShapeLayer to subview
rectangleView.layer.mask = shapeLayer;

By using CAShapelayer we can specify radius for particular corners.

//Set  radius of UIView for Top right and bottom left corners only
UIBezierPath *shapePath =[UIBezierPath bezierPathWithRoundedRect:rectangleView.bounds byRoundingCorners:(UIRectCornerTopRight | UIRectCornerBottomLeft) cornerRadii:CGSizeMake(10, 10)];
    shapeLayer.path = shapePath.CGPath;
    rectangleView.layer.mask = shapeLayer;

Friday, 4 March 2016

UIImagePickerController in Swift

UIImagePickerController  class manages customizable, system-supplied user interface for taking pictures and movies, and for choosing saved images and movies for use in the app. A UIImagePickerController manages user interactions and delivers the results of those interactions to a delegate object.
For more details Click here.

To use an image picker controller with in the app, perform these steps:

1) Verify that the device is capable of picking content from the desired source.
2) Check which media types are available for the source type using.
3) Adjust image picker controller's UI according to media type
4) Present user interface.


Code:

// MARK: - Open Camera
    func openCamera(source:UIImagePickerControllerSourceType){


//Check source type available or not
        if(UIImagePickerController.isSourceTypeAvailable(source) == false){
            return;
        }

//Create new object of UIImagePickerContrller
        let imagepickerController = UIImagePickerController()
       imagepickerController.sourceType = source
        imagepickerController.delegate = self

//Present UIImagePickerContrller user interface
        self.presentViewController(imagepickerController, animated: true, completion: nil)
    }


//MARK: - Image Picker Delegate
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        nameTitlelabel.hidden = false
        //dismiss image picker controller view
        picker.dismissViewControllerAnimated(true, completion: nil)
    }


    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

//Get selected image
        let seletctedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        patientImageView.image = seletctedImage

//dismiss image picker controller view
        picker.dismissViewControllerAnimated(true, completion: nil)
    }