Powered By Blogger
Showing posts with label Objective C. Show all posts
Showing posts with label Objective C. Show all posts

Thursday, March 16, 2017

How to integrate "SwiftLint" library into XCode project ?


Hi everyone,

Now a days, I was looking for a tool which can assist the developers to write code with good quality by following some basic standards. A tool which can throws warnings/errors if developer is not following the code writing rules. I have found multiple tools for multiple platforms. But I have chosen "SwiftLint" for "SWIFT" language, which is the same as its prior version "OCLint" for "Objective C".

A) Steps to integrate :



Please read this article's contents carefully to integrate it successfully and below are the steps :

Step 1 : Install ‘Homebrew’ into your Mac using the below command :

a. /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Step 2 : Install ‘SwiftLint’ package with the help of below command :

a. brew install swiftlint

Step 3 : To Integrate SwiftLint into current Xcode Project, add a new “Run Script” in Build phase with below contents :

if which swiftlint >/dev/null; then
swiftlint
else
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi

Note 1 : Above code will throw a warning if SwiftLint is not installed on the system. But if you want that all your team member will install it, you can make build failed using following script :

if which swiftlint >/dev/null; then
swiftlint
else
echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
exit 1
fi

Note 2 : Now build your project (⌘B). SwiftLint will automatically identify warnings and errors in your code that does not comply with the default style guide line. Finally we have successfully integrated SwiftLint in our current project. But, If you will compile your project, you ended up with lots of warnings and errors. Even Xcode’s “Single View” project template doesn’t pass SwiftLint’s default validation.


B) Auto correct:


Some of the basic issues (such as whitespace at the end of a line) can be automatically fixed by SwiftLint. Just open the terminal and type the following command in your project root directory.

$ cd path/to/project/root/directory
$ swiftlint autocorrect
$ swiftlint autocorrect --path your_file.swift #For SwiftLint's auto correct on single file


C) To configure the behaviour of SwiftLint :


Now we have to fix all other issues that SwiftLint’s autocorrect was not able to do. But fixing all the issues one time it’s too much complex and time consuming. Fortunately, it provides configuration options to ‘enable/disable’ its pre defined rules. So, Initially I will disable all the rules and enable one by one to break down the bigger task into smaller chunks.


To get started, just create '.swiftlint.yml' in your project’s root directory and paste following contents in it.

disabled_rules:
- trailing_newline
- opening_brace
- empty_count
- comma
- colon
- force_cast
- type_name
- variable_name_min_length
- trailing_semicolon
- force_try
- function_body_length
- nesting
- variable_name
- conditional_binding_cascade
- variable_name_max_length
- operator_whitespace
- control_statement
- legacy_constant
- line_length
- return_arrow_whitespace
- trailing_whitespace
- closing_brace
- statement_position
- type_body_length
- todo
- legacy_constructor
- valid_docs
- missing_docs
- file_length
- leading_whitespace

- Some rules have parameters that you can configure, for example the Type Body Length, how many lines of code the body of a type is allowed to be, can be configured like this:

type_body_length:
- 300 # warning
- 400 # error

D) Summary points :

- To list all available SwiftLint’s rules type following command : ‘$ swiftlint rules’

a) All available rules which you can use are here.

b) You can download the example configuration file from here.

c) Followings are the valid rule identifiers, you can use any of them :
(empty_count , redundant_optional_initialization , trailing_semicolon , statement_position , type_name , unused_enumerated , todo , legacy_constant , force_cast , unused_closure_parameter , nimble_operator , number_separator , comma , sorted_imports , implicit_getter , legacy_cggeometry_functions , force_unwrapping , leading_whitespace , cyclomatic_complexity , control_statement , function_body_length , empty_parentheses_with_trailing_closure , dynamic_inline , type_body_length , unused_optional_binding , operator_whitespace , closure_spacing , prohibited_super_call , object_literal , valid_docs , vertical_whitespace , redundant_void_return , large_tuple , trailing_whitespace , mark , empty_parameters , legacy_nsgeometry_functions , shorthand_operator , closing_brace , class_delegate_protocol , colon , closure_parameter_position , nesting , switch_case_on_newline , file_header , conditional_returns_on_newline , trailing_newline , missing_docs , variable_name , redundant_nil_coalescing , private_unit_test , compiler_protocol_init , return_arrow_whitespace , operator_usage_whitespace , attributes , overridden_super_call , vertical_parameter_alignment , first_where , private_outlet , generic_type_name , explicit_init , legacy_constructor , closure_end_indentation , custom_rules , function_parameter_count , syntactic_sugar , trailing_comma , void_return , valid_ibinspectable , opening_brace , line_length , weak_delegate , force_try , redundant_string_enum_value , file_length)


Regards,
Nilesh

Saturday, February 28, 2015

Attributed string for multi-purpose in iPhone SDK.

Hi,
This post is regarding the use of attributed string for multi-purpose. For more, please check below statements.

NSString *mainString = @"iphoneappcode.blogspot.com";
    NSMutableAttributedString * attributedString;
    UILabel *lbl;
    
    //-- Attributed string with Multiple Colour Combinations. - (NSForegroundColorAttributeName)
    
    attributedString = [[NSMutableAttributedString alloc] initWithString: mainString];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,13)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(13,9)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(22,4)];
    
    lbl = (UILabel *)[self.view viewWithTag:1001];
    lbl.attributedText = attributedString;
    
    //-- Attributed string with different size of font. - (NSFontAttributeName)
    
    attributedString = [[NSMutableAttributedString alloc] initWithString:mainString];
    [attributedString addAttribute:NSFontAttributeName
                             value:[UIFont fontWithName:@"Helvetica-Bold" size:16.0f]
                             range:NSMakeRange(5, 8)];
    
    lbl = (UILabel *)[self.view viewWithTag:1002];
    lbl.attributedText = attributedString;
    
    //-- Attributed string with foreground and background colours. -  (NSForegroundColorAttributeName)
    
    UIColor *_blue = [UIColor magentaColor];

    attributedString = [[NSMutableAttributedString alloc] initWithString:mainString];
    [attributedString addAttribute:NSForegroundColorAttributeName value:_blue range:NSMakeRange(0, [mainString length])];
    
    lbl = (UILabel *)[self.view viewWithTag:1003];
    lbl.attributedText = attributedString;
    
    //-- Attributed string with Underlined format. - (NSUnderlineStyleAttributeName)
    
    mainString = @"iphoneappcode.blogspot.com";
    attributedString = [[NSMutableAttributedString alloc] initWithString:mainString];
    [attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(0, [mainString length])];
    
    lbl = (UILabel *)[self.view viewWithTag:1004];
    lbl.attributedText = attributedString;
    
    //-- Attributed string with Background color. - (NSBackgroundColorAttributeName)
    
    mainString = @"iphoneappcode.blogspot.com";
    attributedString = [[NSMutableAttributedString alloc] initWithString:mainString];
    // Set background color for entire range
    [attributedString addAttribute:NSBackgroundColorAttributeName
                             value:[UIColor cyanColor]
                             range:NSMakeRange(0, [attributedString length])];
    
    lbl = (UILabel *)[self.view viewWithTag:1005];
    lbl.attributedText = attributedString;


Regards,

Nilesh M. Prajapati



Thursday, December 18, 2014

Steps to regenerate libzbar library for 64-bit architecture support.

Hi everyone,
After a long time, I'm back to share some useful things with you. In now a days, I'm busy to make my application 64-bit architecture devices support as per apple's guide line which must be followed before 1st February 2015. So, I have started to make third party libraries compatible to 64-bit architecture. For that, I choose libZbar and steps are as defined below : (iPhone 6 & 6 Plus support)
Step 1 : Download the source code (you must have Mercurial for mac):
Step 2 : Open Terminal and run following commands
        b. To Enter zbar directory command : cd zbar
        c. To checkout command : hg checkout iPhoneSDK-1.3.1
        d. To open project use this command : open iphone/zbar.xcodeproj
Step 3 : In the xcode project edit the "libzbar" scheme and select Release in Build configuration
Step 4 : Go to Build Settings set following Architectures
         a. Architectures - > Standard architectures(armv7,armv72,arm64)
         b. Valid Architectures -> arm64,armv7 armv7s
Step 5 : Compile libzbar for device AND for simulator, here the configuration:
Step 6 : Find the compiled libzbar.a and go in the folder using Teminal.app,
In My Case : /Users/Nell/Library/Developer/Xcode/DerivedData/zbar-gyozyrpbqzvslmfoadhqkwskcesd/Build/Products
Step 7 : In this folder, you should have two sub folders namely "Release-iphoneos" and "Release-iphonesimulator".
Step 8 : using xcode command line tools build your universal lib:
      lipo -create Release-iphoneos/libzbar.a Release-iphonesimulator/libzbar.a -o libzbar.a
Now you can use the libzbar.a created, both in device and simulator.

Regards ,
Nilesh M. Prajapati

Monday, January 27, 2014

Asynchronous image downloading with dispatch_async queue

Hi,

There's no need to implement any framework for LazyImage loading as of now. You can do it simply by writing few lines of code below.. Just take a look..


Example : 

UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc]init];
UIImageView * userImage = [[UIImageView alloc]init];

        [activity startAnimating];
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
        dispatch_async(queue, ^(void) {
            //  You may want to cache this explicitly instead of reloading every time.
            NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
            UIImage* image = [[UIImage alloc] initWithData:imageData];
            dispatch_async(dispatch_get_main_queue(), ^{
                // Capture the indexPath variable, not the cell variable, and use that
               userImage.image = image;
                [activity stopAnimating];
            });
       });


Regards,
Nilesh M. Prajapati

Monday, January 13, 2014

how to share information in iPhone?

Hi,
Recently I have integrated UIActivityViewController in my one of the applications for iOS 6.0 and later versions. For iOS 5.1.1, I used default "twitter.framework".
Please check below code to share information in your application through social media.

//******* Place below code into Implementation part *********//

UIPopoverController *popup;
UIActionSheet *actionSheet;

#define HTML_STR @"" //Any html string which you want to set at the time of sending an email for iOS 5.1.1 and below iOS.

#pragma mark -------------------
#pragma mark Share Button Click event
#pragma mark -------------------

-(IBAction)btnShareClick:(id)sender
{
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"6.0"))
    {
        [self showActivityView]; // For iOS 6.0 & later ....
    }
    else
    {
        [self showActionSheet]; // For iOS 5.1.1 & below ....
    }
}

#pragma mark -------------------
#pragma mark UIActivityViewController Delegate methods
#pragma mark -------------------

-(void)showActivityView // For iOS 6.0 & later ....
{
    NSMutableDictionary *dictInfo = [array objectAtIndex:index];
   
    //-- set up the data objects
    NSString *Title = [NSString stringWithFormat:@"Promotion Title : %@\n",[dictInfo valueForKey:@"Title"]];
    NSString *fullAddress = [NSString stringWithFormat:@"%@, %@",[dictInfo valueForKey:@"City"],[dictInfo valueForKey:@"StateName"]];
   NSString *validDate = [NSString stringWithFormat:@"Date : %@ To %@ \n",[dictInfo valueForKey:@"strStartDate"],[dictInfo valueForKey:@"strEndDate"]];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.xyz.com/%@",[dictInfo valueForKey:@"url"]]];
   
    UIImage *image = [UIImage imageNamed:@"title.png"];
    NSArray *activityItems = [NSArray arrayWithObjects:Title,
                              fullAddress,
                              validDate,
                              url,
                              image,nil];
   
    //-- initialising the activity view controller
    UIActivityViewController *activityView = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    //-- define the activity view completion handler
    activityView.completionHandler = ^(NSString *activityType, BOOL completed)
    {
        NSLog(@"Activity Type selected: %@", activityType);
        if (completed)
        {
            NSLog(@"Selected activity was performed.");
        }
        else
        {
            if (activityType == NULL) {
                NSLog(@"User dismissed the view controller without making a selection.");
            }
            else {
                NSLog(@"Activity was not performed.");
            }
        }
      }
    };
   
    //-- define activity to be excluded (if any)
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
        activityView.excludedActivityTypes = [NSArray arrayWithObjects:UIActivityTypeAddToReadingList,UIActivityTypeAirDrop,nil];
    }
    else
    {
        activityView.excludedActivityTypes = [NSArray arrayWithObjects:UIActivityTypeSaveToCameraRoll,nil];
    }
   
    if (IS_IPAD)
    {
        if (self.popup) {
            [self.popup dismissPopoverAnimated:NO];
            popup = nil;
        }
        self.popup = [[UIPopoverController alloc] initWithContentViewController:activityView];
        //UIBarButtonItem *barBtn = (UIBarButtonItem *)[self.navigationItem.rightBarButtonItems objectAtIndex:3];
        self.popup.delegate = self;
        [self.popup presentPopoverFromRect:selectedButton.frame inView:selectedButton.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }
    else
    {
        //-- show the activity view controller
        [self presentViewController:activityView
                           animated:YES completion:^{
                               Appdel.objTab.hidden=YES;
                           }];
    }
}

#pragma mark ------------------------------
#pragma mark UIPopoverController delegate method
#pragma mark ------------------------------

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    if (self.popup) {
        [self.popup dismissPopoverAnimated:NO];
        popup = nil;
    }
}
#pragma mark ------------------------------
#pragma mark UIActionSheet delegate method
#pragma mark ------------------------------

-(void)showActionSheet // For iOS 5.1.1 & below
{
    if (actionSheet) {
        [actionSheet dismissWithClickedButtonIndex:3 animated:YES];
        actionSheet = nil;
    }
    actionSheet = [[UIActionSheet alloc]initWithTitle:@"Share with"
                                             delegate:self
                                    cancelButtonTitle:nil
                               destructiveButtonTitle:nil
                                    otherButtonTitles:@"Email",@"Facebook",@"Twitter",@"Cancel",nil];
    if (IS_IPAD)
    {
        [actionSheet showFromRect:selectedButton.frame inView:selectedButton.superview animated:YES];
    }
    else
    {
        [actionSheet showInView:self.view];
    }
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex // For iOS 5.1.1 & below
{
    switch (buttonIndex)
    {
        case 0:
            NSLog(@"Email");
        {
                [self openMailComposer];
        }
            break;
        case 1:
            NSLog(@"Facebook");
        {
            [Appdel.HUD show:YES];
            [self performSelector:@selector(dofacebookLogin) withObject:nil afterDelay:0.5];
        }
            break;
        case 2:
            NSLog(@"Twitter");
        {
                [self sendTwitToYourAccout];
        }
            break;
        case 3:
            NSLog(@"Cancel");
            break;
        default:
            break;
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet1 didDismissWithButtonIndex:(NSInteger)buttonIndex // For iOS 5.1.1 & below
{
    if (actionSheet) {
        [actionSheet dismissWithClickedButtonIndex:3 animated:YES];
        actionSheet = nil;
    }
}

#pragma mark ------------------------------
#pragma mark MFMailComposeViewController delegate method
#pragma mark ------------------------------


-(void)openMailComposer // For iOS 5.1.1 & below
{
    NSMutableDictionary *dictInfo = [array objectAtIndex:index];
  
    NSString *Title = [NSString stringWithFormat:@"Title : %@</br></br>",[dictInfo valueForKey:@"Title"]];
    NSString *fullAddress = [NSString stringWithFormat:@"%@, %@",[dictInfo valueForKey:@"City"],[dictInfo valueForKey:@"State"]];
    NSString *validDate = [NSString stringWithFormat:@"Date : %@ To %@ </br></br>",[dictInfo valueForKey:@"strStartDate"],[dictInfo valueForKey:@"strEndDate"]];
  
    NSString *strUrl = [NSString stringWithFormat:@"http://www.xyz.com/%@",[dictInfo valueForKey:@"url_name"]];
    NSString *combinedString = [NSString stringWithFormat:@"%@ %@ %@ %@",Title,fullAddress,validDate,strUrl];
    NSString *string = [NSString stringWithFormat:HTML_STR,combinedString,strUrl,[dictInfo valueForKey:@"ImageUrl"]];
  
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
    [picker setSubject:@"Send Mail"];
  
    NSArray *toRecipients = [NSArray arrayWithObject:@""];
    [picker setToRecipients:toRecipients];
  
    NSString *emailBody = [NSString stringWithFormat:@"%@",string];
    [picker setMessageBody:emailBody isHTML:YES];
      
    picker.navigationBar.tintColor=[UIColor colorWithRed:0.976 green:0.612 blue:0.067 alpha:1];
    [self presentModalViewController:picker animated:YES];
    picker = nil;
    toRecipients = nil;
}

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    [controller dismissModalViewControllerAnimated:NO];
}

#pragma mark ------------------------------
#pragma mark TWTweetComposeViewController delegate method
#pragma mark ------------------------------

-(void)sendTwitToYourAccout// For iOS 5.1.1 & below
{
    if ([TWTweetComposeViewController canSendTweet])
    {
        NSMutableDictionary *dictInfo = [array objectAtIndex:index];
       
        NSString *promotionTitle = [NSString stringWithFormat:@"Title : %@",[dictInfo valueForKey:@"Title"]];
        NSString *validDate = [NSString stringWithFormat:@"Date : %@ To %@",[dictInfo valueForKey:@"strStartDate"],[dictInfo valueForKey:@"strEndDate"]];
        NSString *strUrl = [NSString stringWithFormat:@"http://www.xyz.com/%@",[dictInfo valueForKey:@"url_name"]];
       
        // Initialize Tweet Compose View Controller
        TWTweetComposeViewController *vc = [[TWTweetComposeViewController alloc] init];
        // Settin The Initial Text
        [vc setInitialText:[NSString stringWithFormat:@"%@\n %@",Title,validDate]];
       
        // Adding an Image
        UIImage *image = [UIImage imageNamed:@"title.png"];
        [vc addImage:image];
       
        // Adding a URL
        NSURL *url = [NSURL URLWithString:strUrl];
        [vc addURL:url];
       
        // Setting a Completing Handler
        [vc setCompletionHandler:^(TWTweetComposeViewControllerResult result) {
            [self dismissModalViewControllerAnimated:YES];
        }];
       
        // Display Tweet Compose View Controller Modally
        [self presentViewController:vc animated:YES completion:nil];
    }
    else
    {
        // Show Alert View When The Application Cannot Send Tweets
        NSString *message = @"The application cannot send a tweet at the moment. This is because it cannot reach Twitter or you don't have a Twitter account associated with this device.";
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Warning !" message:message delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
        [alertView show];
    }
}

#pragma mark ------------------------------
#pragma mark FacebookSDK delegate method
#pragma mark ------------------------------

-(void) dofacebookLogin // For iOS 5.1.1 & below
{
    [SCFacebook loginCallBack:^(BOOL success, id result) {
        if (success) {
            [self sendFeedTofacebook];
        }
        else
        {
            Alert(@"Warning !", result);
        }
    }];
}

- (void)sendFeedTofacebook // For iOS 5.1.1 & below
{
        NSMutableDictionary *dictPromotionInfo = [array objectAtIndex:index];
        NSString *Title = [NSString stringWithFormat:@"Title : %@\n",[dictInfo valueForKey:@"Title"]];
        UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dictInfo valueForKey:@"Image"]]]];
      
        NSString *validDate = [NSString stringWithFormat:@"Date : %@ To %@ \n",[dictInfo valueForKey:@"strStartDate"],[dictInfo valueForKey:@"strEndDate"]];

        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.xyz.com/%@",[dictInfo valueForKey:@"url_name"]]];
      
        [SCFacebook feedPostWithPhoto:image caption:[NSString stringWithFormat:@"%@ %@ %@ %@",Title,validDate,url] callBack:^(BOOL success, id result)
         {
             if (success) {
                 Alert(@"Info !", @"Your feed has been posted successfully over Facebook.");
             }
             else
             {
                 Alert(@"Warning !", result);
             }
         }];
}


Thanks & Regards,
-----------------------------
Nilesh M. Prajapati

Tuesday, February 19, 2013

Best printer sdk for iPhone

Hey everyone,
Now I found one more good things regarding printing in iPhone SDK. I found "STAR MACRONICS" printers having their own SDKs for Both iOS and android devices. By using this SDK, You can easily integrate POS printers and as well as bluetooth, USB printers with your application.

Please take a look to below given link from where you can download SDK and its manual for integration.


Documentation link http://www.starmicronics.com/support/SDKDocumentation.aspx


Regards,
Nilesh Prajapati

Friday, December 7, 2012

how to make custom segmented control?

Hi,
Many of you want to make custom controls in their own projects but sometime they need some guidance or the way to customize those controls. So, here is the way for everyone who wants to make his/her own custom segmented control in iPhone, iPad projects. Please follow the below steps :

Step 1 : Import these two files in your projects . ("CustomsegmentControl.h","CustomsegmentControl.m")

#import <UIKit/UIKit.h>

@interface CustomSegmentControl : UISegmentedControl
{
    UIColor *unselectedColor,*selectedColor;
}
@property (nonatomic,retain) UIColor *unselectedColor,*selectedColor;
-(id)initWithItems:(NSArray *)items unselectedColor:(UIColor*)unselectedColor selectedColor:(UIColor*)selectedColor;
@end


#import "CustomSegmentControl.h"

@interface CustomSegmentControl(private)
-(void)setupInitialMode;
-(void)switchHighlightColors;
@end

@implementation CustomSegmentControl

@synthesize unselectedColor,selectedColor;

-(id)initWithItems:(NSArray *)items unselectedColor:(UIColor*)unselectedColor selectedColor:(UIColor*)selectedColor {
    if (self = [super initWithItems:items])
    {
        // Initialization code
        self.unselectedColor = unselectedColor;
        self.selectedColor = selectedColor;
        [self setInitialMode];
        [self setSelectedSegmentIndex:0];
    }
    return self;
}
- (void)awakeFromNib
{
    self.unselectedColor = [UIColor colorWithWhite:0.7 alpha:1];
    self.selectedColor = self.tintColor;
    [self setInitialMode];
   
    [self setSelectedSegmentIndex:0];
}

-(void)setupInitialMode
{
    [self setBackgroundColor:[UIColor clearColor]];
    [self setSegmentedControlStyle:UISegmentedControlStyleBar];
   
    for( int i = 0; i < [self.subviews count]; i++ )
    {
        [[self.subviews objectAtIndex:i] setTintColor:nil];
        [[self.subviews objectAtIndex:i] setTintColor:unselectedColor];
    }
    [self addTarget:self action:@selector(switchHighlightColors) forControlEvents:UIControlEventValueChanged];
}


-(void)switchHighlightColors
{
    for (id view in self.subviews) {
        if ([view isSelected]) [view setTintColor:selectedColor];
        else [view setTintColor:unselectedColor];
    }
}

- (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex
{
    [super setSelectedSegmentIndex:selectedSegmentIndex];
    [self switchHighlightColors];
}
@end

Step 2 :  Now make your new custom segment control in the class file wherever you want to use that custom control. 

For example : CustomSegmentControl *obj_customsegment;

obj_customsegment = [[CustomSegmentControl alloc]initWithItems:[NSArray arrayWithObjects:@"One",@"Two",nil] unselectedColor:[UIColor blackColor] selectedColor:[UIColor blueColor]];


Now, you can easily use above custom segment control object in your project.

Regards,
Nilesh Prajapati

Tuesday, November 27, 2012

how to change the selected segment button color ?

Hi all,
Please use the below code if you want to change the color of UISegmentedControl's component after the selection of that rather showing the default color.

For example : 

UISegmentedControl *segmentedControl; // You can use your own segmented control rather using this one...

UIColor *selectedColor = [UIColor colorWithRed: 0.0f/255.0 green:0.0f/255.0 blue:255.0f/255.0 alpha:1.0];
         UIColor *deselectedColor = [UIColor colorWithRed: 0.0f/255.0 green: 0.0f/255.0 blue: 255.0/255.0 alpha:0.2];

for (id subview in [segmentedControl subviews]) {
    if ([subview isSelected])
       [subview setTintColor:selectedColor];
    else
       [subview setTintColor:deselectedColor];
}


Thanks,
Nilesh Prajapati

how to add gradient effect to button in iphone?

Hi friends,
If anyone, of you, want to add gradient effect to custom button then here is the way to add that effect.

Example :

        // Add Border to button
        CALayer *layer = btnCalender.layer;
        layer.cornerRadius = 5.0f;
        layer.masksToBounds = YES;
        layer.borderWidth = 1.0f;
        layer.borderColor = [UIColor colorWithWhite:0.3f alpha:0.2f].CGColor;
       
        // Add Shine to button
        CAGradientLayer *Layer = [CAGradientLayer layer];
        Layer = layer.bounds;
        Layer.colors = [NSArray arrayWithObjects:
                             (id)[UIColor colorWithWhite:1.0f alpha:0.4f].CGColor,
                             (id)[UIColor colorWithWhite:1.0f alpha:0.2f].CGColor,
                             (id)[UIColor colorWithWhite:0.75f alpha:0.2f].CGColor,
                             (id)[UIColor colorWithWhite:0.4f alpha:0.2f].CGColor,
                             (id)[UIColor colorWithWhite:1.0f alpha:0.4f].CGColor,
                             nil];
        Layer.locations = [NSArray arrayWithObjects:
                                [NSNumber numberWithFloat:0.0f],
                                [NSNumber numberWithFloat:0.2f],
                                [NSNumber numberWithFloat:0.3f],
                                [NSNumber numberWithFloat:0.0f],
                                [NSNumber numberWithFloat:1.0f],
                                nil];
        [layer addSublayer: Layer];

Regards, 
Nilesh Prajapati

Saturday, November 24, 2012

how to use NSDateFormatter for different format?

 Hi,
Using the below category for NSDate, you can use below functions to get various date format string or date.

 #import <Foundation/Foundation.h>

@interface NSDate(TCUtils)

- (NSDate *)TC_dateByAddingCalendarUnits:(NSCalendarUnit)calendarUnit amount:(NSInteger)amount;
- (NSString*)TC_dateindisplayformat:(NSString*) format;
- (NSString*)TC_datewithTformat:(NSString*)dt format:(NSString*) format;
- (NSString*)TC_dateformat:(NSString*)dt format:(NSString*) format;
- (NSDate*)TC_stringformat:(NSString*)dt format:(NSString*) format;
- (NSString*)TC_date24format:(NSString*)dt format:(NSString*) format;
- (NSDate*)TC_datewithTformat:(NSString*)dt;
- (BOOL)isSameDay:(NSDate*)anotherDate;
- (NSDate *) todayDateWithoutTime;
@end



#import "NSDate+TCUtils.h"

@implementation NSDate (TCUtils)


- (NSDate *)TC_dateByAddingCalendarUnits:(NSCalendarUnit)calendarUnit amount:(NSInteger)amount {
    NSDateComponents *components = [[NSDateComponents alloc] init];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *newDate;
   
    switch (calendarUnit) {
        case NSSecondCalendarUnit:
            [components setSecond:amount];
            break;
        case NSMinuteCalendarUnit:
            [components setMinute:amount];
            break;
        case NSHourCalendarUnit:
            [components setHour:amount];
            break;
        case NSDayCalendarUnit:
            [components setDay:amount];
            break;
        case NSWeekCalendarUnit:
            [components setWeek:amount];
            break;
        case NSMonthCalendarUnit:
            [components setMonth:amount];
            break;
        case NSYearCalendarUnit:
            [components setYear:amount];
            break;
        default:
            ////NSLog(@"addCalendar does not support that calendarUnit!");
            break;
    }
   
    newDate = [gregorian dateByAddingComponents:components toDate:self options:0];
    [components release];
    [gregorian release];
    return newDate;
}

- (NSString*)TC_dateindisplayformat:(NSString*) format
{
    NSDateFormatter* df=[[[NSDateFormatter alloc] init] autorelease];
    [df setTimeZone:[NSTimeZone defaultTimeZone]];
    NSLocale *locale = [[[NSLocale alloc]
                         initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; 
    [df setLocale:locale];
    [df setDateFormat:format];
    return [df stringFromDate:self];   
}

- (NSString*)TC_datewithTformat:(NSString*)dt format:(NSString*) format
{
    NSDateFormatter* df=[[[NSDateFormatter alloc] init] autorelease];
    [df setTimeZone:[NSTimeZone defaultTimeZone]];
    NSLocale *locale = [[[NSLocale alloc]
                         initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; 
    [df setLocale:locale];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSArray* a=[dt componentsSeparatedByString:@"T"];
    NSDate* tdt;
    if([a count]>0){
        tdt=[df dateFromString:[a objectAtIndex:0]];
    }
    else{
        tdt=[NSDate date];
    }
    [df setDateFormat:format];
   
    return [df stringFromDate:tdt];
}

- (NSString*)TC_dateformat:(NSString*)dt format:(NSString*) format
{
    NSDateFormatter* df=[[[NSDateFormatter alloc] init] autorelease];
    [df setTimeZone:[NSTimeZone defaultTimeZone]];
    NSLocale *locale = [[[NSLocale alloc]
                         initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; 
    [df setLocale:locale];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSDate* tdt=[df dateFromString:dt];
    [df setDateFormat:format];
   
    return [df stringFromDate:tdt];
}

- (NSDate*)TC_stringformat:(NSString*)dt format:(NSString*) format
{
    NSDateFormatter* df=[[[NSDateFormatter alloc] init] autorelease];
    [df setTimeZone:[NSTimeZone defaultTimeZone]];
    NSLocale *locale = [[[NSLocale alloc]
                         initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; 
    [df setLocale:locale];
    [df setDateFormat:format];

    return [df dateFromString:dt];
}

- (NSDate*)TC_datewithTformat:(NSString*)dt
{
    NSDateFormatter* df=[[[NSDateFormatter alloc] init] autorelease];
    [df setTimeZone:[NSTimeZone defaultTimeZone]];
    NSLocale *locale = [[[NSLocale alloc]
                         initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
    [df setLocale:locale];
    dt=[dt stringByReplacingOccurrencesOfString:@"T" withString:@" "];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [df dateFromString:dt];
}

- (NSString*)TC_date24format:(NSString*)dt format:(NSString*) format
{
    NSDateFormatter* df=[[[NSDateFormatter alloc] init] autorelease];
    [df setTimeZone:[NSTimeZone defaultTimeZone]];
    NSLocale *locale = [[[NSLocale alloc]
                         initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; 
    [df setLocale:locale];
    [df setDateFormat:@"yyyy-MM-dd hh:mm a"];
    NSDate* tdt=[df dateFromString:dt];
    [df setDateFormat:format];
   
    return [df stringFromDate:tdt];
}

- (NSDate *) todayDateWithoutTime
{
    NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
      [df setTimeZone:[NSTimeZone  defaultTimeZone]];
    NSLocale *locale = [[[NSLocale alloc]
                         initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
    [df setLocale:locale];
    [df setDateFormat:@"yyyy-MM-dd"];

    NSString *todayDateS = [df stringFromDate:[NSDate date]];
    NSDate *todayDate = [df dateFromString:todayDateS];
    return todayDate;
}



- (BOOL)isSameDay:(NSDate*)anotherDate{
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components1 = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self];
    NSDateComponents* components2 = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:anotherDate];
    return ([components1 year] == [components2 year] && [components1 month] == [components2 month] && [components1 day] == [components2 day]);
}

@end

Tuesday, October 30, 2012

how to check iPhone volume programmatically?

Hi everyone,
Below is the trick to check the iPhone/iPad/iPod Touch (iOS Device) volume level. Please take a look..

#import <AudioToolbox/AudioToolbox.h>

    Float32 volume;
    UInt32 dataSize = sizeof(Float32);
    AudioSessionGetProperty (
                             kAudioSessionProperty_CurrentHardwareOutputVolume,
                             &dataSize,
                             &volume
                             );
    NSLog(@"Volume Level : %f",volume);
    if (volume <= 0.25)
    {
              NSLog(@"Volume is below %d \%",(volume*100));
    }

Thanks,
Nilesh M. Prajapati

how to create UUID in iPhone?

Hi friends,
Here is the example for creating UUID in your iPhone/iPad/iPod Touch application.

            NSString *deviceUuid = nil;
            CFStringRef cfUuid = CFUUIDCreateString(NULL, CFUUIDCreate(NULL));
            deviceUuid = (NSString *)cfUuid;
            NSLog(@"deviceUuid : %@",deviceUuid);
            CFRelease(cfUuid);

Now , you can use this "deviceUuid" as UUID.

Thanks,
Nilesh M. Prajapati

Saturday, October 20, 2012

how to implement MPMoviePlayerViewController in iPhone?

Hi every one,
Please take a look at MPMoviePlayerController integration for local/live video playing in iPhone/iPad/iPod Touch (iOS 4.0 and later..).

Step 1 : Add "MediaPlayer.framework" into your project resource.
Step 2 :  Import <MediaPlayer/MediaPlayer.h> into your class where you want to use MediaPlayer for playing videos (local/live).
Step 3 : Place below code into the controller class where you want to integrate player.

-(IBAction)btnVideoClicked:(id)sender
{
    @try
    {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
        GetVideos *obj_video = [arrVideos objectAtIndex:[sender tag]];
        MPMoviePlayerViewController *moviePlayerViewController = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:obj_video.VideoPath]];
        [moviePlayerViewController.moviePlayer setControlStyle:MPMovieControlStyleFullscreen];
        [moviePlayerViewController.moviePlayer setShouldAutoplay:YES];
        [moviePlayerViewController.moviePlayer setFullscreen:NO animated:YES];
        [moviePlayerViewController setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
        [moviePlayerViewController.moviePlayer setScalingMode:MPMovieScalingModeNone];
        [moviePlayerViewController.moviePlayer setUseApplicationAudioSession:NO];
        // Register to receive a notification when the movie has finished playing. 
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector:@selector(moviePlaybackStateDidChange:) 
                                                     name:MPMoviePlayerPlaybackStateDidChangeNotification 
                                                   object:moviePlayerViewController];
        // Register to receive a notification when the movie has finished playing. 
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector:@selector(moviePlayBackDidFinish:) 
                                                     name:MPMoviePlayerPlaybackDidFinishNotification 
                                                   object:moviePlayerViewController];
        [self presentMoviePlayerViewControllerAnimated:moviePlayerViewController];
        moviePlayerViewController.moviePlayer.movieSourceType = MPMovieSourceTypeStreaming;
        [moviePlayerViewController release];
        [pool release];
    }
    @catch (NSException *exception) {
        // throws exception
    }
}


#pragma mark -----------------------
#pragma mark MPMoviePlayer Notification Methods


-(void)moviePlaybackStateDidChange:(NSNotification *)notification
{

    MPMoviePlayerViewController *moviePlayerViewController = [notification object]; 

    if (moviePlayerViewController.moviePlayer.loadState == MPMovieLoadStatePlayable &&
        moviePlayerViewController.moviePlayer.playbackState != MPMoviePlaybackStatePlaying)
    {
        [moviePlayerViewController.moviePlayer play];
    }
   
    // Register to receive a notification when the movie has finished playing. 
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                 name:MPMoviePlayerPlaybackStateDidChangeNotification 
                                               object:moviePlayerViewController];
    moviePlayerViewController = nil;
}

- (void) moviePlayBackDidFinish:(NSNotification*)notification

    MPMoviePlayerViewController *moviePlayerViewController = [notification object]; 
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:MPMoviePlayerPlaybackDidFinishNotification 
                                                  object:moviePlayerViewController]; 
    [self dismissMoviePlayerViewControllerAnimated];
    moviePlayerViewController = nil;


Thanks ,
Nilesh M. Prajapati

Tuesday, October 16, 2012

How to make paging in iPhone?

Hi,
Here is the example of horizontal paging using UIScrollView and its property pagingEnabled.

Look at the below code :

- (void)viewDidLoad
{
    [super viewDidLoad];
    pageCount = 0;
    scrollView.pagingEnabled = YES;
}

#pragma mark ---------------------
#pragma mark User-Defined Methods

-(void)GenerateVideoThumbnail
{
    for (UIView *videoView in self.scrollView.subviews)
    {
        [videoView removeFromSuperview];
        videoView = nil;
    }

    CGFloat X = 12.5,Y = 5.0; // Button X and Y position
    CGFloat Width = 90.0,Height = 90.0;
    CGFloat XDiff = 12.5,YDiff = 5.0;
    NSInteger MaxIconPerRow = 3;  
    NSInteger MaxIconPerPage = 12;

    for (int i=0; i<[arrVideos count]; i++)
    {
        GetVideos *obj_video = [arrVideos objectAtIndex:i];
        UIButton *btnVideo = [UIButton buttonWithType:UIButtonTypeCustom];
        btnVideo.tag = i;
        NSLog(@"frame X: %f, Y: %f",btnVideo.frame.origin.x,btnVideo.frame.origin.y);
        [btnVideo setBackgroundImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:obj_video.Thumnailpath]]] forState:UIControlStateNormal];

        btnVideo.frame = CGRectMake(X, Y, Width, Height);
        [self.scrollView addSubview:btnVideo];
        [btnVideo startLoading];
        btnVideo = nil;
       
        X = X + Width + XDiff;
        if((i+1)%MaxIconPerRow ==0)
        {
            X = (pageCount*320.0) + XDiff;
            Y = Y + Height + YDiff;
        }
        if((i+1)%MaxIconPerPage ==0)
        {
            ++pageCount;
            X = (pageCount*320.0) + XDiff;
            Y = 5.0;
        }
    }
    self.scrollView.contentSize = CGSizeMake((pageCount*self.scrollView.frame.size.width), self.scrollView.frame.size.height);
}

Thursday, October 4, 2012

How to add custom fonts to iPhone application?

Hi,

As of iOS 4.0 and later iOS version came, it has become very easy to add custom fonts to your iPhone/iPad/iPod applications. Here, some steps you have to follow in order to add custom fonts:

    1.    Add your custom font files into your project using XCode as a resource
    2.    Add a key to your info.plist file called UIAppFonts.
    3.    Make this key an array
    4.    For each font you have, enter the full name of your font file (including the extension) as items
           to the UIAppFonts array.
    5.    Save info.plist
    6.    Now in your application you can simply call
           [UIFont  fontWithName:@"CustomFontName" size:FontSize]
           to get the custom font to use with your UILabels and UITextViews, etc…

It’s very simple to integrate!

Thursday, September 27, 2012

UIPanGestureRecognizer scrolling example for iOS

Hi everyone,
Today, I'm giving you the source code of UIPanGestureRecognizer for iPhone.



Follow 2-3 simple steps as given below:

1) Put below code into your .header file of any viewcontroller class.

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIGestureRecognizerDelegate>
{
    IBOutlet UIView *viewOrange;
    IBOutlet UIView *viewBrown;
    IBOutlet UIView *viewPurple;
}
@property(nonatomic,retain) IBOutlet UIView *viewOrange;
@property(nonatomic,retain) IBOutlet UIView *viewBrown;
@property(nonatomic,retain) IBOutlet UIView *viewPurple;

@end

2) Put below code into your .m file of same viewcontroller class.

#import "ViewController.h"

@implementation ViewController
@synthesize viewOrange;
@synthesize viewBrown;
@synthesize viewPurple;

CGPoint translatedPoint;
NSInteger _firstX;
NSInteger _firstY;
NSInteger numberofView;
CGSize viewSize;
float currentView;

BOOL isBegan;


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
  
    numberofView = 3;
    viewSize = CGSizeMake(320.0, 480.0);
   
    viewOrange.frame = CGRectMake(0.0, 0.0, 320.0, 480.0);
    viewPurple.frame = CGRectMake(320.0, 0.0, 320.0, 480.0);
    viewBrown.frame = CGRectMake(640.0, 0.0, 320.0, 480.0);
   
    UISwipeGestureRecognizer *swipegestureRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipe:)];
    [swipegestureRecognizer setDelegate:self];
    [self.view addGestureRecognizer:swipegestureRecognizer];
    [swipegestureRecognizer release];

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


-(IBAction)handleSwipe:(UIPanGestureRecognizer *)sender
{
    translatedPoint = [sender translationInView:self.view];

        if([sender state] == UIGestureRecognizerStateBegan)
        {
            if (self.viewOrange.frame.origin.x >= -((numberofView-1)*viewSize.width) && self.viewOrange.frame.origin.x <= 0.0)
            {
                _firstX = self.viewOrange.frame.origin.x;
                _firstY = self.viewOrange.frame.origin.y;
               
                if (viewOrange.frame.origin.x==0) {
                    currentView=0;
                }else if (viewPurple.frame.origin.x==0) {
                    currentView=1;
                }else if (viewBrown.frame.origin.x==0) {
                    currentView=2;
                }

            }
        }
        else if([sender state] == UIGestureRecognizerStateChanged)
        {
            if ([sender velocityInView:self.view].x >= 600.0)
            {
                if (!isBegan)
                {
                    if (self.viewOrange.frame.origin.x < 0.0)
                    {
                        isBegan = YES;
                        NSLog(@"Velocity Changed.");
                        [UIView beginAnimations:nil context:NULL];
                        [UIView setAnimationDuration:0.2];
                        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                        [viewOrange setFrame:CGRectMake(viewOrange.frame.origin.x + viewOrange.frame.size.width, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                        viewPurple.frame = CGRectMake(viewOrange.frame.origin.x + viewOrange.frame.size.width, 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                        viewBrown.frame = CGRectMake(viewPurple.frame.origin.x + viewPurple.frame.size.width, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                        [UIView commitAnimations];
                    }
                }
            }
            else if ([sender velocityInView:self.view].x <= -600.0)
            {
                if (!isBegan)
                {
                    if (self.viewOrange.frame.origin.x > -((numberofView-1)*viewSize.width))
                    {
                        isBegan = YES;
                        NSLog(@"Velocity Changed.");
                        [UIView beginAnimations:nil context:NULL];
                        [UIView setAnimationDuration:0.2];
                        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                        [viewOrange setFrame:CGRectMake(viewOrange.frame.origin.x - viewOrange.frame.size.width, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                        viewPurple.frame = CGRectMake(viewOrange.frame.origin.x + viewOrange.frame.size.width, 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                        viewBrown.frame = CGRectMake(viewPurple.frame.origin.x + viewPurple.frame.size.width, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                        [UIView commitAnimations];
                    }
                }
            }
            else
            {
                if (self.viewOrange.frame.origin.x >= -((numberofView-1)*viewSize.width) && self.viewOrange.frame.origin.x <= 0.0)
                {
                    NSLog(@"State Changed.");
                    [UIView beginAnimations:nil context:NULL];
                    [UIView setAnimationDuration:0.2];
                    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                    translatedPoint = CGPointMake(_firstX + translatedPoint.x, 0.0);
                    [viewOrange setFrame:CGRectMake(translatedPoint.x, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                    viewPurple.frame = CGRectMake(viewOrange.frame.origin.x + viewOrange.frame.size.width, 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                    viewBrown.frame = CGRectMake(viewPurple.frame.origin.x + viewPurple.frame.size.width, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                    [UIView commitAnimations];
                }
            }
        }
        else if([sender state] == UIGestureRecognizerStateEnded)
        {
            NSLog(@"State Ended On That ");
            if (self.viewOrange.frame.origin.x >= -((numberofView-1)*viewSize.width) && self.viewOrange.frame.origin.x <= 0.0)
            {
                NSLog(@"%f",viewOrange.frame.origin.x);
                NSLog(@"%f",viewPurple.frame.origin.x);
                NSLog(@"%f",viewBrown.frame.origin.x);
                if (currentView==0) {
                    if (viewOrange.frame.origin.x<0 ){
                        if (viewOrange.frame.origin.x<-160) {
                            [UIView beginAnimations:nil context:NULL];
                            [UIView setAnimationDuration:0.2];
                            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                            [viewOrange setFrame:CGRectMake(-320, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                            viewPurple.frame = CGRectMake(viewOrange.frame.size.width+viewOrange.frame.origin.x , 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                            [UIView commitAnimations];
                        }else{
                           
                            [UIView beginAnimations:nil context:NULL];
                            [UIView setAnimationDuration:0.2];
                            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                            [viewOrange setFrame:CGRectMake(0.0, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                            viewPurple.frame = CGRectMake(320, 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                            [UIView commitAnimations];
                        }
                    }
                }else if(currentView==1){
                    if (viewPurple.frame.origin.x<0){
                        if (viewPurple.frame.origin.x<-160) {
                           
                            [UIView beginAnimations:nil context:NULL];
                            [UIView setAnimationDuration:0.2];
                            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                            [viewOrange setFrame:CGRectMake(-640, 0.0, viewOrange.frame.size.width,  viewOrange.frame.size.height)];
                            viewPurple.frame = CGRectMake(-320 , 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                            viewBrown.frame = CGRectMake(0.0, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                            [UIView commitAnimations];
                           
                          

                        }else {
                            [UIView beginAnimations:nil context:NULL];
                            [UIView setAnimationDuration:0.2];
                            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                            [viewOrange setFrame:CGRectMake(-320.0, 0.0, viewOrange.frame.size.width,  viewOrange.frame.size.height)];
                            viewPurple.frame = CGRectMake(0.0 , 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                            viewBrown.frame = CGRectMake(320.0, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                            [UIView commitAnimations];
                        }
                    }else{
                         if (viewPurple.frame.origin.x>160) {
                             [UIView beginAnimations:nil context:NULL];
                             [UIView setAnimationDuration:0.2];
                             [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                             [viewOrange setFrame:CGRectMake(0.0, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                             viewPurple.frame = CGRectMake(320 , 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                             viewBrown.frame = CGRectMake(640.0, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                             [UIView commitAnimations];

                         }else{
                            
                             [UIView beginAnimations:nil context:NULL];
                             [UIView setAnimationDuration:0.2];
                             [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                             [viewOrange setFrame:CGRectMake(-320.0, 0.0, viewOrange.frame.size.width,  viewOrange.frame.size.height)];
                             viewPurple.frame = CGRectMake(0.0 , 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                             viewBrown.frame = CGRectMake(320.0, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                             [UIView commitAnimations];
                            
                        }
                    }
                }else if(currentView==2){
                    if (viewBrown.frame.origin.x>0){
                       
                        if (viewBrown.frame.origin.x>160) {
                            [UIView beginAnimations:nil context:NULL];
                            [UIView setAnimationDuration:0.2];
                            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                            [viewOrange setFrame:CGRectMake(-320.0, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                            viewPurple.frame = CGRectMake(0.0 , 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                            viewBrown.frame = CGRectMake(320.0, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                            [UIView commitAnimations];
                        }else{
                            [UIView beginAnimations:nil context:NULL];
                            [UIView setAnimationDuration:0.2];
                            [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                            [viewOrange setFrame:CGRectMake(-640, 0.0, viewOrange.frame.size.width,  viewOrange.frame.size.height)];
                            viewPurple.frame = CGRectMake(-320 , 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                            viewBrown.frame = CGRectMake(0.0, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                            [UIView commitAnimations];
                           
                        }
                      
                    }
                }
            }
            isBegan = NO;
            if (self.viewOrange.frame.origin.x <-((numberofView-1)*viewSize.width))
            {
                NSLog(@"State Changed.");
                [UIView beginAnimations:nil context:NULL];
                [UIView setAnimationDuration:0.2];
                [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                [viewOrange setFrame:CGRectMake(-640.0, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                viewPurple.frame = CGRectMake(viewOrange.frame.origin.x + viewOrange.frame.size.width, 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                viewBrown.frame = CGRectMake(viewPurple.frame.origin.x + viewPurple.frame.size.width, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                [UIView commitAnimations];
            }
            else if (self.viewOrange.frame.origin.x > 0)
            {
                NSLog(@"State Changed.");
                [UIView beginAnimations:nil context:NULL];
                [UIView setAnimationDuration:0.2];
                [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
                [viewOrange setFrame:CGRectMake(0.0, 0.0, viewOrange.frame.size.width, viewOrange.frame.size.height)];
                viewPurple.frame = CGRectMake(viewOrange.frame.origin.x + viewOrange.frame.size.width, 0.0, viewPurple.frame.size.width, viewPurple.frame.size.height);
                viewBrown.frame = CGRectMake(viewPurple.frame.origin.x + viewPurple.frame.size.width, 0.0, viewBrown.frame.size.width, viewBrown.frame.size.height);
                [UIView commitAnimations];
            }
        }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


@end

 Thanks,
Nilesh Prajapati