Powered By Blogger
Showing posts with label iPhone Programming. Show all posts
Showing posts with label iPhone Programming. Show all posts

Wednesday, May 14, 2014

How to print log for debug mode only in iOS application?

Hi,
Everyone,

Sometimes, we wish to print console in our code for DEBUG mode only. Somehow, We also forget to remove that line from our code too at the time of execution of our product. 


So, I found better solution which helps you to overcome this situation. Please keep below code in your common file and use it anywhere in your code or put it in .pch file of your project.



/******* Start Here ********/

#ifdef DEBUG
# define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define DLog(...)
#endif

// ALog always displays output regardless of the DEBUG setting

#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);

/******* End Here ********/


**** For Example : 

NSString *str = @"https://www.apple.com"
DLog(@"%@",str);

Console : https://www.apple.com



Regards,
Nilesh M. Prajapati

Wednesday, March 26, 2014

how to store event in native calendar of iPhone with EventKit?

Hi,
Here, I'm going to share some lines of code by which you can add an event to native calendar of an iPhone/iPad/iPod touch.  So, please prefer below code to make this functionality visible to your project.

========================================================================

Step 1: Import these framework into your project.
#import <EventKit/EventKit.h>
#import <EventKitUI/EventKitUI.h>

Step 2: Now add below code to your working viewcontroller class. But before doing this make sure that you declare some necessary variables.

-(IBAction)addEventToCalendar:(id)sender
{
    if (!self.defaultCalendar)
    {
        self.eventStore = [[EKEventStore alloc]init];
        self.defaultCalendar = [self.eventStore defaultCalendarForNewEvents];
    }
    // save to iphone calendar
    if([self.eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) // >= iOS 6.0
    {
        // iOS 6 and later
        // This line asks user's permission to access his calendar
        [self.eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
         {
             if (granted) // user user is ok with it
             {
                 [self openCalendarEditViewController];
             }
         }
         else // if he does not allow
         {
             [self performSelectorOnMainThread:@selector(callAccessAlert) withObject:nil waitUntilDone:YES];
             return;
         }
         
         }];
    }
    else // < iOS 6.0
    {
        [self openCalendarEditViewController];
    }
}

-(void)openCalendarEditViewController
{
    NSString *address = @“”; // Address of place where the event will be hold
    NSString *businessUrl = @“”; //Url which you want to add with calendar event
    
    NSDate *startdate; //start date and time of event
    NSDate *enddate = //end date and time of event
    NSString *strNotes; //Add notes which you want to share in with Calendar event
    
    EKEventEditViewController  *addController = [[EKEventEditViewController alloc] init];
    // set the addController's event store to the current event store.
    EKEvent *event = [EKEvent eventWithEventStore:self.eventStore];
    event.title = @“”;//title of an event should be unique to display appointments separately
    event.notes = strNotes;
    event.location = address;
    event.URL = [NSURL URLWithString:businessUrl];
    
    event.startDate = startdate;
    event.endDate = enddate;//[startdate dateByAddingTimeInterval:duration];
    
    NSDate *alarmDate = [startdate dateByAddingTimeInterval:-3600];
    NSArray *arrAlarm = [NSArray arrayWithObject:[EKAlarm alarmWithAbsoluteDate:alarmDate]];
    event.alarms= arrAlarm;
    
    [event setCalendar:self.defaultCalendar];
    
    addController.event = event;
    addController.eventStore = self.eventStore;
    addController.modalPresentationStyle = UIModalPresentationPageSheet;
    addController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    addController.editViewDelegate = self;
    addController.navigationBar.tintColor=[UIColor colorWithRed:0.976 green:0.612 blue:0.067 alpha:1];
    // present EventsAddViewController as a modal view controller
    [self presentModalViewController:addController animated:YES];
}

- (void)requestAccessToEntityType:(EKEntityType)entityType completion:(EKEventStoreRequestAccessCompletionHandler)completion
{
}

// Overriding EKEventEditViewDelegate method to update event store according to user actions.
- (void)eventEditViewController:(EKEventEditViewController *)controller
          didCompleteWithAction:(EKEventEditViewAction)action {
    NSError *error = nil;
    EKEvent *thisEvent = controller.event;
    switch (action) {
        case EKEventEditViewActionCanceled:
            // Edit action canceled, do nothing.
            break;
        case EKEventEditViewActionSaved:
            // When user hit "Done" button, save the newly created event to the event store,
            // and reload table view.
            // If the new event is being added to the default calendar, then update its
            // eventsList.
        {
            NSError *err = nil;
            BOOL isSuceess=[controller.eventStore saveEvent:controller.event span:EKSpanThisEvent error:&error];
        }
            break;
        case EKEventEditViewActionDeleted:
            // When deleting an event, remove the event from the event store,
            // and reload table view.
            // If deleting an event from the currenly default calendar, then update its
            // eventsList.
            [controller.eventStore removeEvent:thisEvent span:EKSpanThisEvent error:&error];
            break;
        default:
            break;
    }
    // Dismiss the modal view controller
    [controller dismissModalViewControllerAnimated:YES];
}

// Set the calendar edited by EKEventEditViewController to our chosen calendar - the default calendar.
- (EKCalendar *)eventEditViewControllerDefaultCalendarForNewEvents:(EKEventEditViewController *)controller {
    EKCalendar *calendarForEdit = self.defaultCalendar;
    return calendarForEdit;

}

------------------

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

Friday, December 6, 2013

How to change image tint color in iphone sdk?

Hi all,


This category takes an image (presumably flat and solid-colored, like a toolbar icon), and fills its non-transparent pixels with a given color. You can optionally also specify a fractional opacity at which to composite the original image over the color-filled region, to give a tinting effect.

This is very useful for generating multiple different-colored versions of the same image, for example 'disabled' or 'highlighted' states of the same basic image, without having to make multiple different-colored bitmap image files.

So, Just make two different files named as : "UIImage+Tint.h" and  "UIImage+Tint.m"


1) For  "UIImage+Tint.h" contents will be ..

#import <UIKit/UIKit.h>

@interface UIImage (ImageTint)

- (UIImage *)imageTintedWithColor:(UIColor *)color;
@end


2) For  "UIImage+Tint.m" contents will be ..
 
#import "UIImage+Tint.h"

@implementation UIImage (ImageTint)

- (UIImage *)imageTintedWithColor:(UIColor *)color
{
    if (color) {
        // Construct new image the same size as this one.
        UIImage *image;
        UIGraphicsBeginImageContextWithOptions([self size], NO, 0.0); // 0.0 for scale means "scale for device's main screen".
        CGRect rect = CGRectZero;
        rect.size = [self size];
       
        // tint the image
        [self drawInRect:rect];
        [color set];
        UIRectFillUsingBlendMode(rect, kCGBlendModeMultiply);
       
        // restore alpha channel
        [self drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1.0f];
       
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
       
        return image;
    }
   
    return self;
}
@end

3) Now you can import "UIImage+Tint.h" file into your class where you want colorful images and do below code.

   UIImage *imgMail = [UIImage imageNamed:@"icon_mail.png"];
    imgMail = [imgMail imageTintedWithColor:MENU_COLOR]; //Colorful image


Important Note : Images will be preferred transparent only .

Thanks,
Nilesh M. Prajapati


Tuesday, October 22, 2013

How can we extract numbers from a string in iPhone?

Hi,

Here is the way to separate numbers from a mixed character string. For this , anybody can use "NSScanner" in their own way. I use this one to filter numbers from the given input string. Please have look ...

For Example : 

NSString *string = @"45#%ds32(())_*x 34";
NSMutableString *newStrStrip = [NSMutableString
        stringWithCapacity:newStrStrip.length];

NSScanner *scanner = [NSScanner scannerWithString:string];
NSCharacterSet *numbers = [NSCharacterSet
        characterSetWithCharactersInString:@"0123456789"];

while ([scanner isAtEnd] == NO)
{
  NSString *buffer;
      if ([scanner scanCharactersFromSet:numbers intoString:&buffer])
     {
          [newStrStrip appendString:buffer];
     }
     else
     {
          [scanner setScanLocation:([scanner scanLocation] + 1)];
     }
}

NSLog(@"OUTPUT : %@", newStrStrip);  // "OUTPUT : 453234"


Regards,
Nilesh M. Prajapati

Saturday, July 20, 2013

Custom switch in iPhone

Hi,
In my recent project, I need to make a custom switch having different colors depending upon theme selection.
Now , I have a solution for that... Make two class files with extension ".h" & ".m". Original Content is available at  HERE. I have made some modifications to the original contents as per my requirements.

SECTION 1 :
 -------------------------------------------------

#import <UIKit/UIKit.h>

@interface CustomSwitch : UIControl

@property(nonatomic, retain) UIColor *tintColor;
@property(nonatomic, retain) UIColor *onTintColor;
@property(nonatomic, assign) UIColor *offTintColor;
@property(nonatomic, assign) UIColor *thumbTintColor;
@property(nonatomic,getter=isOn) BOOL on;


- (id)initWithFrame:(CGRect)frame;
- (void)setOn:(BOOL)on animated:(BOOL)animated;

@end


SECTION 2 :
  -------------------------------------------------

#import "CustomSwitch.h"
#import <QuartzCore/QuartzCore.h>


@interface CustomSwitch () <UIGestureRecognizerDelegate> 

{
    CAShapeLayer *_thumbLayer;
    CAShapeLayer *_fillLayer;
    CAShapeLayer *_backLayer;
    BOOL _dragging;
    BOOL _on;
}
@property (nonatomic, assign) BOOL pressed;
- (void) setBackgroundOn:(BOOL)on animated:(BOOL)animated;
- (void) showFillLayer:(BOOL)show animated:(BOOL)animated;
- (CGRect) thumbFrameForState:(BOOL)isOn;
@end

@implementation
CustomSwitch

 
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self configure];
    }
    return self;
}

- (void) awakeFromNib {
    [self configure];
}

- (void) configure {
    //Check width > height
    if (self.frame.size.height > self.frame.size.width*0.65) {
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, ceilf(0.6*self.frame.size.width));
    }
   
    [self setBackgroundColor:[UIColor clearColor]];
    self.onTintColor = [UIColor colorWithRed:0.27f green:0.85f blue:0.37f alpha:1.00f];
    self.tintColor = [UIColor colorWithRed:0.90f green:0.90f blue:0.90f alpha:1.00f];
    _on = NO;
    _pressed = NO;
    _dragging = NO;
   
   
    _backLayer = [[CAShapeLayer layer] retain];
    _backLayer.backgroundColor = [[UIColor clearColor] CGColor];
    _backLayer.frame = self.bounds;
    _backLayer.cornerRadius = self.bounds.size.height/2.0;
    CGPathRef path1 = [UIBezierPath bezierPathWithRoundedRect:_backLayer.bounds cornerRadius:floorf(_backLayer.bounds.size.height/2.0)].CGPath;
    _backLayer.path = path1;
    [_backLayer setValue:[NSNumber numberWithBool:NO] forKey:@"isOn"];
    _backLayer.fillColor = [_tintColor CGColor];
    [self.layer addSublayer:_backLayer];
   
    _fillLayer = [[CAShapeLayer layer] retain];
    _fillLayer.backgroundColor = [[UIColor clearColor] CGColor];
    _fillLayer.frame = CGRectInset(self.bounds, 1.5, 1.5);
    CGPathRef path = [UIBezierPath bezierPathWithRoundedRect:_fillLayer.bounds cornerRadius:floorf(_fillLayer.bounds.size.height/2.0)].CGPath;
    _fillLayer.path = path;
    [_fillLayer setValue:[NSNumber numberWithBool:YES] forKey:@"isVisible"];
    _fillLayer.fillColor = [[UIColor whiteColor] CGColor];
    [self.layer addSublayer:_fillLayer];
   
   
    _thumbLayer = [[CAShapeLayer layer] retain];
    _thumbLayer.backgroundColor = [[UIColor clearColor] CGColor];
    _thumbLayer.frame = CGRectMake(1.0, 1.0, self.bounds.size.height-2.0, self.bounds.size.height-2.0);
    _thumbLayer.cornerRadius = self.bounds.size.height/2.0;
    CGPathRef knobPath = [UIBezierPath bezierPathWithRoundedRect:_thumbLayer.bounds cornerRadius:floorf(_thumbLayer.bounds.size.height/2.0)].CGPath;
    _thumbLayer.path = knobPath;
    _thumbLayer.fillColor = [UIColor whiteColor].CGColor;
    _thumbLayer.shadowColor = [UIColor blackColor].CGColor;
    _thumbLayer.shadowOffset = CGSizeMake(0.0, 2.0);
    _thumbLayer.shadowRadius = 3.0;
    _thumbLayer.shadowOpacity = 0.1;
    [self.layer addSublayer:_thumbLayer];
   
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                            action:@selector(tapped:)];
    [tapGestureRecognizer setDelegate:self];
    [self addGestureRecognizer:tapGestureRecognizer];
   
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                                            action:@selector(toggleDragged:)];
    //[panGestureRecognizer requireGestureRecognizerToFail:tapGestureRecognizer];
    [panGestureRecognizer setDelegate:self];
    [self addGestureRecognizer:panGestureRecognizer];
   
    [tapGestureRecognizer release];
    [panGestureRecognizer release];
}

#pragma mark -
#pragma mark Animations


- (BOOL) isOn {
    return _on;
}

- (void) setOn:(BOOL)on {
    [self setOn:on animated:NO];
}

- (void)setOn:(BOOL)on animated:(BOOL)animated {
   
    if (_on != on) {
        _on = on;
        [self sendActionsForControlEvents:UIControlEventValueChanged];
    }
    if (animated) {
        [CATransaction begin];
        [CATransaction setAnimationDuration:0.3];
        [CATransaction setDisableActions:NO];
        _thumbLayer.frame = [self thumbFrameForState:_on];
        [CATransaction commit];
    }else {
        [CATransaction setDisableActions:YES];
        _thumbLayer.frame = [self thumbFrameForState:_on];
    }
    [self setBackgroundOn:_on animated:animated];
    [self showFillLayer:!_on animated:animated];
}

- (void) setBackgroundOn:(BOOL)on animated:(BOOL)animated {
    BOOL isOn = [[_backLayer valueForKey:@"isOn"] boolValue];
    if (on != isOn) {
        [_backLayer setValue:[NSNumber numberWithBool:on] forKey:@"isOn"];
        if (animated) {
            CABasicAnimation *animateColor = [CABasicAnimation animationWithKeyPath:@"fillColor"];
            animateColor.duration = 0.22;
            animateColor.fromValue = on ? (id)_tintColor.CGColor : (id)_onTintColor.CGColor;
            animateColor.toValue = on ? (id)_onTintColor.CGColor : (id)_tintColor.CGColor;
            animateColor.removedOnCompletion = NO;
            animateColor.fillMode = kCAFillModeForwards;
            [_backLayer addAnimation:animateColor forKey:@"animateColor"];
            [CATransaction commit];
        }else {
            [_backLayer removeAllAnimations];
            _backLayer.fillColor = on ? _onTintColor.CGColor : _tintColor.CGColor;
        }
    }
}

- (void) showFillLayer:(BOOL)show animated:(BOOL)animated {
    BOOL isVisible = [[_fillLayer valueForKey:@"isVisible"] boolValue];
    if (isVisible != show) {
        [_fillLayer setValue:[NSNumber numberWithBool:show] forKey:@"isVisible"];
        CGFloat scale = show ? 1.0 : 0.0;
        if (animated) {
            CGFloat from = show ? 0.0 : 1.0;
            CABasicAnimation *animateScale = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
            animateScale.duration = 0.22;
            animateScale.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(from, from, 1.0)];
            animateScale.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(scale, scale, 1.0)];
            animateScale.removedOnCompletion = NO;
            animateScale.fillMode = kCAFillModeForwards;
            animateScale.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
            [_fillLayer addAnimation:animateScale forKey:@"animateScale"];
        }else {
            [_fillLayer removeAllAnimations];
            _fillLayer.transform = CATransform3DMakeScale(scale,scale,1.0);
        }
    }
}

- (void) setPressed:(BOOL)pressed {
    if (_pressed != pressed) {
        _pressed = pressed;
       
        if (!_on) {
            [self showFillLayer:!_pressed animated:YES];
        }
    }
}

#pragma mark -
#pragma mark Appearance


- (void) setTintColor:(UIColor *)tintColor {
    _tintColor = [tintColor retain];
    if (![[_backLayer valueForKey:@"isOn"] boolValue]) {
        _backLayer.fillColor = [_tintColor CGColor];
    }
}

- (void) setOnTintColor:(UIColor *)onTintColor {
    _onTintColor = [onTintColor retain];
    if ([[_backLayer valueForKey:@"isOn"] boolValue]) {
        _backLayer.fillColor = [_onTintColor CGColor];
    }
}

- (void) setOffTintColor:(UIColor *)offTintColor {
    _fillLayer.fillColor = [offTintColor CGColor];
}

- (UIColor *) offTintColor {
    return [UIColor colorWithCGColor:_fillLayer.fillColor];
}

- (void) setThumbTintColor:(UIColor *)thumbTintColor {
    _thumbLayer.fillColor = [thumbTintColor CGColor];
}

- (UIColor *) thumbTintColor {
    return [UIColor colorWithCGColor:_thumbLayer.fillColor];
}

#pragma mark -
#pragma mark Interaction


- (void)tapped:(UITapGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateEnded)
        [self setOn:!self.on animated:YES];
}

- (void)toggleDragged:(UIPanGestureRecognizer *)gesture
{
    CGFloat minToggleX = 1.0;
    CGFloat maxToggleX = self.bounds.size.width-self.bounds.size.height+1.0;
   
    if (gesture.state == UIGestureRecognizerStateBegan)
    {
        self.pressed = YES;
        _dragging = YES;
    }
    else if (gesture.state == UIGestureRecognizerStateChanged)
    {
        CGPoint translation = [gesture translationInView:self];
       
        [CATransaction setDisableActions:YES];
       
        self.pressed = YES;
       
        CGFloat newX = _thumbLayer.frame.origin.x + translation.x;
        if (newX < minToggleX) newX = minToggleX;
        if (newX > maxToggleX) newX = maxToggleX;
        _thumbLayer.frame = CGRectMake(newX,
                                       _thumbLayer.frame.origin.y,
                                       _thumbLayer.frame.size.width,
                                       _thumbLayer.frame.size.height);
       
        if (CGRectGetMidX(_thumbLayer.frame) > CGRectGetMidX(self.bounds)
            && ![[_backLayer valueForKey:@"isOn"] boolValue]) {
            [self setBackgroundOn:YES animated:YES];
        }else if (CGRectGetMidX(_thumbLayer.frame) < CGRectGetMidX(self.bounds)
                  && [[_backLayer valueForKey:@"isOn"] boolValue]){
            [self setBackgroundOn:NO animated:YES];
        }
       
       
        [gesture setTranslation:CGPointZero inView:self];
    }
    else if (gesture.state == UIGestureRecognizerStateEnded)
    {
        CGFloat toggleCenter = CGRectGetMidX(_thumbLayer.frame);
        [self setOn:(toggleCenter > CGRectGetMidX(self.bounds)) animated:YES];
        _dragging = NO;
        self.pressed = NO;
    }
   
    CGPoint locationOfTouch = [gesture locationInView:self];
    if (CGRectContainsPoint(self.bounds, locationOfTouch))
        [self sendActionsForControlEvents:UIControlEventTouchDragInside];
    else
        [self sendActionsForControlEvents:UIControlEventTouchDragOutside];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
   
    self.pressed = YES;
   
    [self sendActionsForControlEvents:UIControlEventTouchDown];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    if (!_dragging) {
        self.pressed = NO;
    }
    [self sendActionsForControlEvents:UIControlEventTouchUpInside];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesCancelled:touches withEvent:event];
    if (!_dragging) {
        self.pressed = NO;
    }
    [self sendActionsForControlEvents:UIControlEventTouchUpOutside];
}

#pragma mark -
#pragma mark Thumb Frame


- (CGRect) thumbFrameForState:(BOOL)isOn {
    return CGRectMake(isOn ? self.bounds.size.width-self.bounds.size.height+1.0 : 1.0,
                      1.0,
                      self.bounds.size.height-2.0,
                      self.bounds.size.height-2.0);
}

#pragma mark -
#pragma mark Dealloc

- (void) dealloc {
    [_tintColor release], _tintColor = nil;
    [_onTintColor release], _onTintColor = nil;
   
    [_thumbLayer release], _thumbLayer = nil;
    [_fillLayer release], _fillLayer = nil;
    [_backLayer release], _backLayer = nil;
    [super dealloc];
}

@end
 

Thanks ,
Nilesh M. Prajapati

Monday, July 1, 2013

Custom refresh control in iPhone

Hi,
Everyone,

Did you ever use "Custom Refresh Control" in your iOS application? I recently implemented this concept in my one of code. There's a ready-made control available called "ODRefreshControl"

You just need to import to files into your project resource. "ODRefreshControl.h" & "ODRefreshControl.m". Please check below lines to use it in your code.

*******For Example :

1) Import Files : "ODRefreshControl.h" & "ODRefreshControl.m"
2) Put this into your class file.

- (void)viewDidLoad
{

    ODRefreshControl *refreshControl = [[ODRefreshControl alloc] initInScrollView:tbl_tableView]; // Assign your view in which you want to use it. I used it in my UITableViewController.
    [refreshControl addTarget:self action:@selector(dropViewDidBeginRefreshing:)  forControlEvents:UIControlEventValueChanged];

 [super viewDidLoad];
}

#pragma mark ---------------
#pragma mark UITableView Pull-To-Refresh Management
#pragma mark ---------------

- (void)dropViewDidBeginRefreshing:(ODRefreshControl *)refreshControl
{
    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [refreshControl endRefreshing];
          // write your own refresh method here which you want to call.
    });
}

Thanks,
Nilesh M. Prajapati

Saturday, June 1, 2013

How to show direction inside a Mapview with iOS 6.0 in iphone?

Hey everyone,
  --- Now, with iOS 6.0 , To show direction from source - destination location in Apple's map application. Please check the below code to show the direction into MKMapView.

*** For Example :

CLLocationCoordinate2D coordinate;
coordinate.latitude = 0.0f; // Latitude of your source location
coordinate.longitude = 0.0f; // Longitude of your source location

        MKPlacemark* place = [[MKPlacemark alloc] initWithCoordinate: coordinate addressDictionary: nil];
        MKMapItem* destination = [[MKMapItem alloc] initWithPlacemark: place];
        destination.name = @"Address of your destination";
        NSArray* items = [[NSArray alloc] initWithObjects: destination, nil];
        NSDictionary* options = [[NSDictionary alloc] initWithObjectsAndKeys:
                                 MKLaunchOptionsDirectionsModeDriving,
                                 MKLaunchOptionsDirectionsModeKey, nil];
        [MKMapItem openMapsWithItems: items launchOptions: options];



Thanks,
Nilesh M. Prajapati

Thursday, May 23, 2013

What should be the alternative of horizontal scrolling table in iOS?

Hi,
Dear readers,

Now a days, I came across a new requirement of horizontal scrolling table view. I made some research for it and I found a new library as a unique solution for this. The library is known as "iCarousel" library. You just need to add that 2 files into your project source and after then you can import ".h"(header) file in your class where-ever you want to make such view effect.

Download Link : https://github.com/nicklockwood/iCarousel



After downloading two source files "iCarousel.h" & "iCarousel.m". Follow the below steps to integrate it in your project.

*** Step 1: Create a view of iCarousel in header file and bind it with .XIB file.
    - For ex. : IBOutlet iCarousel *carousel;

*** Step 2: Then place its data-source and delegate methods in implementation section of a view controller.

*** Step 3: Set the delegate of a iCarousel.

*** Step 4: Set the type of a iCarousel in ViewDidLoad method.

- (void)viewDidLoad
{
       [super viewDidLoad];

        carousel.type = iCarouselTypeLinear;
        carousel.vertical = NO;
        carousel.scrollOffset = 1.0;
        carousel.centerItemWhenSelected = NO;
        carousel.stopAtItemBoundary = YES;
        carousel.scrollToItemBoundary = NO;
}

***Step 5: And finally put the below code into implementation section of a view controller.

#pragma mark -------------------
#pragma mark iCarousel Delegate methods
#pragma mark -------------------


- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
    //generate 100 buttons
    //normally we'd use a backing array
    //as shown in the basic iOS example
    //but for this example we haven't bothered
    return [businessArr count];
}

- (UIView *)carousel:(iCarousel *)carousel1 viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
        //create new view if no view is available for recycling
        CustomBusinessListingCell_iPad *businessListingView  = (CustomBusinessListingCell_iPad *)[[[NSBundle mainBundle]loadNibNamed:@"CustomBusinessListingCell_iPad" owner:self options:nil] objectAtIndex:0];
        businessListingView.frame =  CGRectMake(0, 0, LIST_VIEW_WIDTH, LIST_VIEW_HEIGHT);
        businessListingView.tag = index;
        businessListingView.lblBusinessName.verticalAlignment = BAVerticalAlignmentBottom;

        businessListingView.btnBook.tag = index;
        [businessListingView.btnBook addTarget:self action:@selector(btnBookClicked:) forControlEvents:UIControlEventTouchUpInside];
       
        businessListingView.btnBookmark.tag = index;
        [businessListingView.btnBookmark addTarget:self action:@selector(priceClicked:) forControlEvents:UIControlEventTouchUpInside];
       
         //NSLog(@"BusinessImage : %@",[[businessArr objectAtIndex:index] valueForKey:@"BusinessImage"]);
       
        [businessListingView setBusinessValue:[businessArr objectAtIndex:index]];
       
        if (index==[businessArr count]-1)
        {
            // ask next page only if we haven't reached last page
            if([businessArr count] < totalRecords)
            {
                if (!isLoadmore)
                {
                    isLoadmore = YES;
                    pageIndex = pageIndex+1;
                    [self loadNewData];
                }
            }
        }
        return businessListingView;
}

-(void)setCarouselPosition
{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
    if ((orientation == UIInterfaceOrientationPortrait) || (orientation == UIInterfaceOrientationPortraitUpsideDown)) {
        [carousel scrollToOffset:0.6 duration:0.0];
    }
    else if((orientation == UIInterfaceOrientationLandscapeLeft) || (orientation == UIInterfaceOrientationLandscapeRight))
    {
        [carousel scrollToOffset:1.1 duration:0.0];
    }
}

- (CGFloat)carousel:(iCarousel *)_carousel valueForOption:(iCarouselOption)option withDefault:(CGFloat)value
{
    //customize carousel display
    switch (option)
    {
        case iCarouselOptionSpacing:
        {
            //add a bit of spacing between the item views
            return value * 1.08f;
        }
        case iCarouselOptionVisibleItems:
        {
            return 5;
        }
        default:
        {
            return value;
        }
    }
}

- (void)carouselDidEndScrollingAnimation:(iCarousel *)carousel1
{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
    if ((orientation == UIInterfaceOrientationPortrait) || (orientation == UIInterfaceOrientationPortraitUpsideDown)) {
        if (carousel1.scrollOffset < 0.6) {
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDuration:0.7];
            [carousel1 scrollToOffset:0.6 duration:0.0];
            [UIView commitAnimations];
        }
    }
    else if ((orientation == UIInterfaceOrientationLandscapeLeft) || (orientation == UIInterfaceOrientationLandscapeRight))
    {
        if (carousel1.scrollOffset < 1.1) {
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDuration:0.7];
            [carousel1 scrollToOffset:1.1 duration:0.0];
            [UIView commitAnimations];
        }
    }
}

- (void)carouselDidEndDragging:(iCarousel *)carousel1 willDecelerate:(BOOL)decelerate
{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
    if ((orientation == UIInterfaceOrientationPortrait) || (orientation == UIInterfaceOrientationPortraitUpsideDown)) {
        if (carousel1.scrollOffset < 0.6) {
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDuration:0.7];
            [carousel1 scrollToOffset:0.6 duration:0.0];
            [UIView commitAnimations];
        }
    }
    else if ((orientation == UIInterfaceOrientationLandscapeLeft) || (orientation == UIInterfaceOrientationLandscapeRight))
    {
        if (carousel1.scrollOffset < 1.1) {
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDuration:0.7];
            [carousel1 scrollToOffset:1.1 duration:0.0];
            [UIView commitAnimations];
        }
    }
}

Thanks,
Nilesh M. Prajapati

How to resolve apple's UDID issue for Push Notification in iPhone?

Hi,
Everyone,

Rumors say that Apple starts to prohibit the use of UDID in iOS applications from iOS 6.0 and onwards. You can use below solution for  < & >=  iOS 6.0 .

- The device token (used by APNS) and the UDID are two different things. They have nothing to do with each other.

- You obtain the device token for push notifications in your app delegate's application:didRegisterForRemoteNotificationsWithDeviceToken: method.


- The documentation notes the following:
The device token is different from the uniqueIdentifier property of UIDevice because, for security and privacy reasons, it must change when the device is wiped.


#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

NSString *deviceID = nil;

#pragma mark -------------------
#pragma mark UIApplication methods
#pragma mark -------------------

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if (![[NSUserDefaults standardUserDefaults] valueForKey:@"UUID"]) {
        if (SYSTEM_VERSION_LESS_THAN(@"6.0")) {
            self.deviceID = [[self GetUUID] retain];
        }
        else{
            NSUUID* udid= [UIDevice currentDevice].identifierForVendor;
            self.deviceID = [[udid UUIDString] retain];
        }
        [[NSUserDefaults standardUserDefaults] setValue:self.deviceID forKey:@"UUID"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    else{
        self.deviceID = [[[NSUserDefaults standardUserDefaults] valueForKey:@"UUID"] retain];
    }
}

#pragma mark -------------------
#pragma mark Push notification methods
#pragma mark -------------------

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    //NSLog(@"My token is: %@", deviceToken);
    NSString *devicetoken = [[[[deviceToken description]
                               stringByReplacingOccurrencesOfString:@"<"withString:@""]
                              stringByReplacingOccurrencesOfString:@">" withString:@""]
                             stringByReplacingOccurrencesOfString: @" " withString: @""];
    [self updateToken:devicetoken];
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    //NSLog(@"Failed to get token, error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // get state
    UIApplicationState state=[application applicationState];
    if(state== UIApplicationStateActive)
        self.badgeCount=[[[userInfo valueForKey:@"aps"] valueForKey:@"badge"] intValue];
    else
        self.badgeCount= [UIApplication sharedApplication].applicationIconBadgeNumber;
}

- (NSString *)GetUUID
{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return [(NSString *)string autorelease];
}

Thanks, 
Nilesh M. Prajapati

Monday, January 7, 2013

NSPredicate to filter data in iPhone

Hi,
Please check the below lines for filtering a content of an array using "NSPredicate".

Example:

//For Boolean value checking in Array containing dictionaries.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(isCheck == %@)",@"true"];
NSArray *filterArr = [tmpArray filteredArrayUsingPredicate:predicate];

NSPredicate *filter = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"ServiceLevel = '0'"]];        
NSArray *filteredArray = [[tmpArray filteredArrayUsingPredicate:filter]copy];











Thanks

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