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

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, 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!

Monday, October 1, 2012

Mask animation in iPhone

Hi,
Here is the sample code for "Mask Animation" in Objective C and iPhone/iPad/iPod.

#import <UIKit/UIKit.h>

typedef void (^animationCompletionBlock)(void);
#define kAnimationCompletionBlock @"animationCompletionBlock"

@interface ViewController : UIViewController
{
  BOOL animationInFlight;
  IBOutlet UIImageView *imageView;
}
@property (nonatomic) BOOL animationInFlight;

- (IBAction)MaskAnimation:(id)sender;


@end

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



@interface ViewController ()

- (void) removePauseForLayer: (CALayer *) theLayer;
@end

@implementation ViewController


@synthesize animationInFlight;

#pragma mark - view lifecycle methods

- (void)viewDidLoad
{
  [super viewDidLoad];
}


//We only support portrait and portrait upside down orientations
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
  return UIInterfaceOrientationIsPortrait(interfaceOrientation);
}


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

#pragma mark - Instance methods

- (IBAction)MaskAnimation:(id)sender;
{
    animationCompletionBlock theBlock;
    imageView.hidden = FALSE;//Show the image view
   
    //Create a shape layer that we will use as a mask for the  image view
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
   
   
   
    CGFloat maskHeight = imageView.layer.bounds.size.height;
    CGFloat maskWidth = imageView.layer.bounds.size.width;
   
   
    CGPoint centerPoint;
    centerPoint = CGPointMake( maskWidth/2, maskHeight/2);
   
    //Make the radius of our arc large enough to reach into the corners of the image view.
    CGFloat radius = sqrtf(maskWidth * maskWidth + maskHeight * maskHeight)/2;
    //  CGFloat radius = MIN(maskWidth, maskHeight)/2;
   
    //Don't fill the path, but stroke it in black.
    maskLayer.fillColor = [[UIColor clearColor] CGColor];
    maskLayer.strokeColor = [[UIColor blackColor] CGColor];
   
    maskLayer.lineWidth = radius; //Make the line thick enough to completely fill the circle we're drawing
    //  maskLayer.lineWidth = 10; //Make the line thick enough to completely fill the circle we're drawing
   
    CGMutablePathRef arcPath = CGPathCreateMutable();
   
    //Move to the starting point of the arc so there is no initial line connecting to the arc
    CGPathMoveToPoint(arcPath, nil, centerPoint.x, centerPoint.y-radius/2);
   
    //Create an arc at 1/2 our circle radius, with a line thickess of the full circle radius
    CGPathAddArc(arcPath,
                 nil,
                 centerPoint.x,
                 centerPoint.y,
                 radius/2,
                 3*M_PI/2,
                 -M_PI/2,
                 NO);
   
    maskLayer.path = arcPath;
   
    //Start with an empty mask path (draw 0% of the arc)
    maskLayer.strokeEnd = 0.0;
   
   
    CFRelease(arcPath);
   
    //Install the mask layer into out image view's layer.
    imageView.layer.mask = maskLayer;
   
    //Set our mask layer's frame to the parent layer's bounds.
    imageView.layer.mask.frame = imageView.layer.bounds;
   
    //Create an animation that increases the stroke length to 1, then reverses it back to zero.
    CABasicAnimation *swipe = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    swipe.duration = 2;
    swipe.delegate = self;
    [swipe setValue: theBlock forKey: kAnimationCompletionBlock];
   
    swipe.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    swipe.fillMode = kCAFillModeForwards;
    swipe.removedOnCompletion = NO;
    swipe.autoreverses = YES;
   
    swipe.toValue = [NSNumber numberWithFloat: 1.0];
   
    self.animationInFlight = TRUE;
  
    //Set up a completion block that will be called once the animation is completed.
    theBlock = ^void(void)
    {   
        imageView.layer.mask = nil;
        self.animationInFlight = FALSE;
        imageView.hidden = TRUE;
       
        if (self.view.layer.speed == 0)
            [self removePauseForLayer: self.view.layer];
    };
   
    /*
     Install the completion block in the animation using the key kAnimationCompletionBlock
     The completion block will be run by in the animation's animationDidStop:finished delegate method.
     This approach doesn't work for animations that are part of a group, unfortunately, since an animation's
     delegate methods don't get called when the animation is part of an animation group
     */
   
    [swipe setValue: theBlock forKey: kAnimationCompletionBlock];
   
    [maskLayer addAnimation: swipe forKey: @"strokeEnd"];
   
}


- (void) removePauseForLayer: (CALayer *) theLayer;
{
    theLayer.speed = 1.0;
    theLayer.timeOffset = 0.0;
    theLayer.beginTime = 0.0;
}

#pragma mark - CAAnimation delegate methods

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
{
  animationCompletionBlock theBlock = [theAnimation valueForKey: kAnimationCompletionBlock];
  if (theBlock)
    theBlock();
}


@end

How to move an object using touch event in iPhone?

Hello friends,
Here is the example regarding moving an object in Objective C or iPhone/iPad/iPod development.


#import <UIKit/UIKit.h>

@interface ImageMoveViewController : UIViewController
{
    IBOutlet UIImageView *photo;
}

@end


#import "ImageMoveViewController.h"

@implementation ImageMoveViewController

/*
 Implement viewDidLoad if you need to do additional setup after loading the view.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    // get touch event
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];
   
    if ([touch view] == photo) {
        // move the image view
        photo.center = touchLocation;
    }
}

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

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}
- (void)dealloc {
    [super dealloc];
}

@end


Thanks,
Nilesh M. Prajapati

Wednesday, August 1, 2012

how to make custom tabbar in iphone?

Hello,
Just like as every time, I'm here to share code regarding "Custom Tabbar" in iPhone/iPad Application.

Please take a look..

Step 1:  Place these two files in to your project... "CustomTabBar.h" and "CustomTabBar.m"

#import <UIKit/UIKit.h>

@interface CustomTabBar : UITabBarController {
    UIButton *btn1;
    UIButton *btn2;
    UIButton *btn3;
    UIButton *btn4;
    UIButton *btn5;
}

@property (nonatomic, retain) UIButton *btn1;
@property (nonatomic, retain) UIButton *btn2;
@property (nonatomic, retain) UIButton *btn3;
@property (nonatomic, retain) UIButton *btn4;
@property (nonatomic, retain) UIButton *btn5;

-(void) hideTabBar;
-(void) addCustomElements;
-(void) selectTab:(int)tabID;

@end


#import "CustomTabBar.h"

@implementation CustomTabBar

@synthesize btn1, btn2, btn3, btn4, btn5;

- (void)viewDidAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self hideTabBar];
    [self addCustomElements];
}

-(void)hideTabBar
{
    for(UIView *view in self.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            view.hidden = YES;
            break;
        }
    }
}

-(void)hideNewTabBar
{
    self.btn1.hidden = 1;
    self.btn2.hidden = 1;
    self.btn3.hidden = 1;
    self.btn4.hidden = 1;
    self.btn5.hidden = 1;
}

- (void)showNewTabBar
{
    self.btn1.hidden = 0;
    self.btn2.hidden = 0;
    self.btn3.hidden = 0;
    self.btn4.hidden = 0;
    self.btn5.hidden = 0;
}

-(void)addCustomElements
{
    // Initialise our two images
    UIImage *btnImage = [UIImage imageNamed:@"NotificationsSelectedBg.png"];
    UIImage *btnImageSelected = [UIImage imageNamed:@"NavBar_01_s.png"];
   
    self.btn1 = [UIButton buttonWithType:UIButtonTypeCustom]; //Setup the button
    btn1.frame = CGRectMake(0, 430, 80, 50); // Set the frame (size and position) of the button)
    [btn1 setBackgroundImage:btnImage forState:UIControlStateNormal]; // Set the image for the normal state of the button
    [btn1 setBackgroundImage:btnImageSelected forState:UIControlStateSelected]; // Set the image for the selected state of the button
    [btn1 setTag:0]; // Assign the button a "tag" so when our "click" event is called we know which button was pressed.
    [btn1 setSelected:true]; // Set this button as selected (we will select the others to false as we only want Tab 1 to be selected initially
   
    // Now we repeat the process for the other buttons
    btnImage = [UIImage imageNamed:@"NotificationsSelectedBg.png"];
    btnImageSelected = [UIImage imageNamed:@"NavBar_02_s.png"];
    self.btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn2.frame = CGRectMake(80, 430, 80, 50);
    [btn2 setBackgroundImage:btnImage forState:UIControlStateNormal];
    [btn2 setBackgroundImage:btnImageSelected forState:UIControlStateSelected];
    [btn2 setTag:1];
   
    btnImage = [UIImage imageNamed:@"NotificationsSelectedBg.png"];
    btnImageSelected = [UIImage imageNamed:@"NavBar_03_s.png"];
    self.btn3 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn3.frame = CGRectMake(160, 430, 80, 50);
    [btn3 setBackgroundImage:btnImage forState:UIControlStateNormal];
    [btn3 setBackgroundImage:btnImageSelected forState:UIControlStateSelected];
    [btn3 setTag:2];
   
    btnImage = [UIImage imageNamed:@"NotificationsSelectedBg.png"];
    btnImageSelected = [UIImage imageNamed:@"NavBar_04_s.png"];
    self.btn4 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn4.frame = CGRectMake(240, 430, 80, 50);
    [btn4 setBackgroundImage:btnImage forState:UIControlStateNormal];
    [btn4 setBackgroundImage:btnImageSelected forState:UIControlStateSelected];
    [btn4 setTag:3];
   
    btnImage = [UIImage imageNamed:@"NotificationsSelectedBg.png"];
    btnImageSelected = [UIImage imageNamed:@"NavBar_04_s.png"];
    self.btn5 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn5.frame = CGRectMake(320, 430, 80, 50);
    [btn5 setBackgroundImage:btnImage forState:UIControlStateNormal];
    [btn5 setBackgroundImage:btnImageSelected forState:UIControlStateSelected];
    [btn5 setTag:4];
   
   
    // Add my new buttons to the view
    [self.view addSubview:btn1];
    [self.view addSubview:btn2];
    [self.view addSubview:btn3];
    [self.view addSubview:btn4];
    [self.view addSubview:btn5];

   
    // Setup event handlers so that the buttonClicked method will respond to the touch up inside event.
    [btn1 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btn2 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btn3 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btn4 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btn5 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)buttonClicked:(id)sender
{
    int tagNum = [sender tag];
    [self selectTab:tagNum];
}

- (void)selectTab:(int)tabID
{
    switch(tabID)
    {
        case 0:
            [btn1 setSelected:true];
            [btn2 setSelected:false];
            [btn3 setSelected:false];
            [btn4 setSelected:false];
            [btn5 setSelected:false];
            break;
        case 1:
            [btn1 setSelected:false];
            [btn2 setSelected:true];
            [btn3 setSelected:false];
            [btn4 setSelected:false];
            [btn5 setSelected:false];
            break;
        case 2:
            [btn1 setSelected:false];
            [btn2 setSelected:false];
            [btn3 setSelected:true];
            [btn4 setSelected:false];
            [btn5 setSelected:false];
            break;
        case 3:
            [btn1 setSelected:false];
            [btn2 setSelected:false];
            [btn3 setSelected:false];
            [btn4 setSelected:true];
            [btn5 setSelected:false];
            break;
        case 4:
            [btn1 setSelected:false];
            [btn2 setSelected:false];
            [btn3 setSelected:false];
            [btn4 setSelected:false];
            [btn5 setSelected:true];
            break;
    }   
    self.selectedIndex = tabID;
}

- (void)dealloc {
    [btn1 release];
    [btn2 release];
    [btn3 release];
    [btn4 release];
    [btn5 release];
    [super dealloc];
}

Step 2 :  If you user XIB base TabBarController then you need to set "CustomTabBar" as its class or otherwise you have to create TabBarController object of "CustomTabBar" class .

Now , you are able to use custom tabbar into user application. one more thing, You have to add the images which you want to assign at your tabbar controller items.

Thanks & Regards,
Nilesh Prajapati

Tuesday, June 5, 2012

How to check valid email address in iPhone SDK?

Using the below function , you can check email address format validity. Hope , this will help you.
 
+(BOOL)checkEmailAddress:(NSString *)strEmail
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}";  
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];  
    return [emailTest evaluateWithObject:strEmail];
}


If any one has query then place you it over here.

Thanks and Regards,
Nilesh Prajapati
 

Wednesday, May 2, 2012

How to get device IPAddess in iPhone SDK?

 Hello friends,
Here is the code which helps to get the Local IPAddress of an iOS device.

#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#include <ifaddrs.h>


// retun the host name
+ (NSString *) hostname
{
    char baseHostName[256];
    int success = gethostname(baseHostName, 255);
    if (success != 0) return nil;
    baseHostName[255] = '\0';
   
#if !TARGET_IPHONE_SIMULATOR
    return [NSString stringWithFormat:@"%s.local", baseHostName];
#else
     return [NSString stringWithFormat:@"%s", baseHostName];
#endif
}

// return IP Address
+ (NSString *) localIPAddress
{
    struct hostent *host = gethostbyname([[self hostname] UTF8String]);
    if (!host) {herror("resolv"); return nil;}
    struct in_addr **list = (struct in_addr **)host->h_addr_list;
    return [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding];
}


If any one has query then place you it over here.

Thanks and Regards,
Nilesh Prajapati
 

Tuesday, May 1, 2012

How to rotate a view in iPhone using QuartzCore.framework?

Hi,
Code regarding the rotation. you can use the below code for simply making rotation to any angle you want. You can also reverse the animation that you want. You need to import "QuartzCore.framework" into your code.

   CABasicAnimation *theAnimation;
    theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    theAnimation.duration=1.0; // Animation duration
    theAnimation.repeatCount=1; // no of times you want to do animation
    theAnimation.autoreverses=YES; // reverses the animation
    theAnimation.fromValue=[NSNumber numberWithFloat:0.0]; // initial stage of animation
    theAnimation.toValue=[NSNumber numberWithFloat:degreesToRadians(360)]; // rotation angle
    [self.view.layer addAnimation:theAnimation forKey:@"animateRotation"]; // add animation to the
 layer of a view for which you want animation.



If any one has query then place you it over here.

Thanks and Regards,
Nilesh Prajapati