Wednesday, October 29, 2014

UIAlertView function overloading

AlertView.h file

#import <Foundation/Foundation.h>

@interface AlertView : NSObject

+ (void)showAlert:(NSString*)message;
+ (void)showAlert:(NSString*)message WithDelegate:(id)delegate;
+ (void)showAlert:(NSString*)message WithDelegate:(id)delegate andTag:(int)tag;

+ (void)showAlert:(NSString*)message WithDelegate:(id)delegate andTag:(int)tag andButtons:(NSString *)buttons;

+ (void)showDiscardAlert:(NSString*)message WithDelegate:(id)delegate andTag:(int)tag andButtons:(NSString *)buttons;


@end

================================
AlertView.m file

#import "AlertView.h"
#define title @"PrognoCIS"

@implementation AlertView

+(void) showAlert: (NSString*)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title 
                    message:message delegate:nil  cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
}

+(void) showAlert: (NSString*)message WithDelegate:(id)delegate
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title   message:message
           delegate:delegate cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
}

+ (void)showAlert:(NSString*)message WithDelegate:(id)delegate andTag:(int)tag
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:delegate
            cancelButtonTitle:@"OK" otherButtonTitles: nil];
    
    [alert setTag:tag];
    [alert show];
}

+ (void)showAlert:(NSString*)message WithDelegate:(id)delegate andTag:(int)tag andButtons:(NSString *)buttons
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message
            delegate:delegate cancelButtonTitle:@"Cancel" otherButtonTitles: buttons, nil];
    
    [alertView setTag:tag];
    [alertView show];
}

+ (void)showDiscardAlert:(NSString*)message WithDelegate:(id)delegate andTag:(int)tag andButtons:(NSString *)buttons
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title 
    message:message delegate:delegate cancelButtonTitle:@"Discard" otherButtonTitles: buttons, nil];
    
    [alertView setTag:tag];
    [alertView show];
}

@end

================================
Usage in any file :

[AlertView showAlert:@"Discard the changes?" WithDelegate:self andTag:3000 andButtons:@"Discard"];

Adjust cell height dynamically in UITableView

#define GET_BOLD_FONT_WITH_SIZE(__SIZE) ([UIFont fontWithName:FONT_BOLD size:__SIZE])

//Method declaration
-(CGSize)calculateCellHeight:(NSString*)text;

//Usage
cellHeight=[self calculateCellHeight:info.textValue];

///////////////////////////////////////////////////
// Method : calculateCellHeight
// Params : text
// Description : To adjust cell height dynamicaly
//////////////////////////////////////////////////

-(CGSize)calculateCellHeight:(NSString*)text{
    
    CGSize height;
    height = [text sizeWithFont:GET_BOLD_FONT_WITH_SIZE(14)
              constrainedToSize:CGSizeMake(300.0, 1000.0)
                  lineBreakMode:UILineBreakModeWordWrap];

    return height;

}

Restrict user from selecting future date in UIDatePickerView

Below function disables the future date in UIDatePickerView 

-(void)setMaximumDateInDatePicker {       

    [dateTimePicker setMinuteInterval:1];   
    
    NSDate* now = [NSDate date] ;
    NSCalendar* calendar = [NSCalendar currentCalendar] ;

    NSDateComponents* nowWithoutSecondsComponents = [calendar components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate:now] ;

    int currentHour=nowWithoutSecondsComponents.hour;
    int currentMinute=nowWithoutSecondsComponents.minute;
    int currentSecond=nowWithoutSecondsComponents.second;
  
    NSDate *maxDate = [[NSDate alloc] initWithTimeIntervalSinceNow:((24-currentHour)*60*60)-((currentMinute*60)+currentSecond+10)];

    dateTimePicker.maximumDate = maxDate ;
    NSLog(@"maxDate : %@ ",maxDate );

}

Tuesday, October 28, 2014

Toggle animation of view (up/down) on button click

In the below code snippet SearchBar toggles up and down with animation effect

[self animateView:DOWN];

////////////////////////////////////////////////////////
// Method : animateView
// Params : direction
// Return : animate the searchview appearance
////////////////////////////////////////////////////////

- (void)animateView:(NSString *)direction {
    
    [self.view bringSubviewToFront:patientSearchbar];
    
    if ([direction isEqualToString:DOWN]) {
        
        CGRect initialFrame = CGRectMake(0, 0 - searchView.frame.size.height  
        + 44, searchView.frame.size.width, searchView.frame.size.height);
        searchView.frame = initialFrame;
        
        searchView.layer.borderColor = VIOLET_BORDER_COLOR;
        searchView.layer.masksToBounds = NO;
        searchView.layer.shadowColor = [[UIColor blackColor] CGColor];
        searchView.layer.shadowOpacity = 1.0;
        searchView.layer.shadowRadius = 10.0;
        searchView.layer.shadowOffset = CGSizeMake(0, 3);
        
        [UIView animateWithDuration:0.5 delay:0.0 
        options:UIViewAnimationOptionCurveEaseOut animations:^{  
            
            CGRect viewRect =  CGRectMake(initialFrame.origin.x
        initialFrame.origin.y + initialFrame.size.height
        initialFrame.size.width, initialFrame.size.height);
           
            searchView.frame = viewRect;
            
        } completion:^(BOOL finished) {
             // Perform completion task here
        }];
        
    } else if ([direction isEqualToString:UP]){
        
        [UIView animateWithDuration:0.5 delay:0.0 
         options:UIViewAnimationOptionCurveEaseOut animations:^{  
       
              CGRect originalFrame = CGRectMake(0, 0
         searchView.frame.size.height + 44, searchView.frame.size.width
         searchView.frame.size.height);
        
         searchView.frame = originalFrame;
            
        } completion:^(BOOL finished) {

            [searchView removeFromSuperview];
        }];
    }

}

Alternative method to check network connectivity using Reachability

Import Reachability file and create an object of Reachability


[self checkReachability];

-(void)checkReachability {
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                selector:@selector(reachabilityChanged:)
                name:kReachabilityChangedNotification object:nil];
    
    reachability = [Reachability reachabilityWithHostName:@"www.google.com"];
    [reachability startNotifier];
}

- (void)reachabilityChanged:(NSNotification* )notification {
    
    Reachability* curReach = [notification object];

    if ([curReach currentReachabilityStatus] == NotReachable{
        NSLog(@"Server not reachable....");
        [self hideOverlay];       
    }
    else {
        NSLog(@"Server reachable ....");
        
    }

}



Create custom navigation bar back button

//**************************************************************************
//Method    : createLeftNavigationButton
//Params    : create the left navigation back button with the image
//Return    :
//**************************************************************************

#define IMAGE(imageName)    (UIImage *)[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName         ofType:IMAGE_TYPE_PNG]]

- (void)createLeftNavigationButton {
    
    //customize right bar button item
    UIView *backButtonView = [[UIView alloc] initWithFrame:NAVIGATION_BAR_BUTTON_RECT];

    [backButtonView setBackgroundColor:[UIColor clearColor]];
    
    UIButton *backButton = [[UIButton alloc] init];
    backButton.frame     = backButtonView.frame;

    [backButton addTarget:self action:@selector(backButtonClick:) 
         forControlEvents:UIControlEventTouchUpInside];

    [backButton setImage:IMAGE(@"backButton") forState:UIControlStateNormal];    
    [backButtonView addSubview:backButton];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]  
                                  initWithCustomView:backButtonView];    

}

Convert hexString to UIColor


//Usage
titleLabel.textColor = [UIColor colorFromHexString:@"#929292"];


//Method definition
- (UIColor *)colorFromHexString:(NSString *)hexString {

    NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];

    if([cleanString length] == 3) {

        cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@"
                       [cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
                       [cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
                       [cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];

    }

    if([cleanString length] == 6) {
        cleanString = [cleanString stringByAppendingString:@"ff"];
    }

    unsigned int baseValue;
    [[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];

    float red = ((baseValue >> 24) & 0xFF)/255.0f;
    float green = ((baseValue >> 16) & 0xFF)/255.0f;
    float blue = ((baseValue >> 8) & 0xFF)/255.0f;
    float alpha = ((baseValue >> 0) & 0xFF)/255.0f;

    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];

}