Powered By Blogger
Showing posts with label iPad. Show all posts
Showing posts with label iPad. Show all posts

Saturday, February 28, 2015

Attributed string for multi-purpose in iPhone SDK.

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

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

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


Regards,

Nilesh M. Prajapati



Monday, March 10, 2014

UICollectionView with dynamic image height

Hi,
Dear readers,

I had successfully used UICollectionView with dynamic heights of images which fetches data from NSURL string. iOS 6.0 and later versions can use "UICollectionView" to make a model like "Water Flow" or "Pinterest Layout".

Please see below steps to have it in your application.


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

*** STEP 1 : 
A. Include these two files into your project source directory.
     1.) " CHTCollectionViewWaterfallLayout.h"
     2.) " CHTCollectionViewWaterfallLayout.m"
B. You can download these files from CHTCollectionViewWaterfallLayout .
C. Import "ImageIO.framework" into project.

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

*** STEP 2:  

A) Generate two class files “CategoryCell.h” and “CategoryCell.m” for UICollectionViewCell.


#import "FXImageView.h"
@interface CategoryCell : UICollectionViewCell

@property (nonatomic, strong) UIButton *btnPhoto;
@property (nonatomic, strong) FXImageView *photoView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIView *bottomView;


#import "CategoryCell.h"

const CGFloat kTMPhotoQuiltViewMargin = 5;

@implementation CategoryCell

@synthesize photoView = _photoView;
@synthesize titleLabel = _titleLabel;
@synthesize btnPhoto = _btnPhoto;
@synthesize bottomView = _bottomView;

#pragma mark - Accessors

- (UILabel *)titleLabel {
if (!_titleLabel) {
_titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, self.contentView.bounds.size.width, 30.0)];
_titleLabel.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
_titleLabel.backgroundColor = [UIColor clearColor];
_titleLabel.textColor = WHITE_COLOR;
        if (IS_IPAD) {
            _titleLabel.font = FONT_BOLD(14.0);
        }
        else
        {
            _titleLabel.font = FONT_BOLD(12.0);
        }
_titleLabel.textAlignment = NSTextAlignmentCenter;
}
return _titleLabel;
}

- (UIView *)bottomView {
if (!_bottomView) {
_bottomView = [[UIView alloc] initWithFrame:CGRectMake(0.0, self.contentView.bounds.size.height - 30.0, self.contentView.bounds.size.width, 30.0)];
_bottomView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
_bottomView.backgroundColor = BLACK_COLOR;
        _bottomView.alpha = 0.6;
}
return _bottomView;
}

- (FXImageView *)photoView {
if (!_photoView) {
_photoView = [[FXImageView alloc] initWithFrame:self.contentView.bounds];
        _photoView.asynchronous = YES;
        _photoView.contentMode = UIViewContentModeScaleAspectFit;
_photoView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
_photoView.backgroundColor = CLEAR_COLOR;
        _photoView.layer.shadowOpacity = 2.0;
        _photoView.layer.shadowColor = LIGHT_GRAY_COLOR.CGColor;
        _photoView.layer.shadowRadius = 2.0;
        _photoView.layer.shadowOffset = CGSizeMake(-0.5, 0.5);
}
return _photoView;
}

- (UIButton *)btnPhoto{
if (!_btnPhoto) {
_btnPhoto = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnPhoto.frame = self.contentView.bounds;
        _btnPhoto.contentMode = UIViewContentModeScaleAspectFill;
_btnPhoto.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
_btnPhoto.backgroundColor = CLEAR_COLOR;
        _btnPhoto.layer.shadowOpacity = 5.0;
        _btnPhoto.layer.shadowColor = LIGHT_GRAY_COLOR.CGColor;
        _btnPhoto.layer.shadowRadius = 5.0;
        _btnPhoto.layer.shadowOffset = CGSizeMake(-1.0, 1.0);
}
return _btnPhoto;
}

#pragma mark - Life Cycle

#if !__has_feature(objc_arc)
- (void)dealloc {
[_photoView removeFromSuperview];
_photoView = nil;
    
    [_titleLabel removeFromSuperview];
_titleLabel = nil;
    
    [super dealloc];
}
#endif

- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self.contentView addSubview:self.photoView];
        [self.contentView addSubview:self.btnPhoto];
        [self.bottomView addSubview:self.titleLabel];
        [self.contentView addSubview:self.bottomView];
}
return self;
}

@end

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

*** STEP 3:  

#import <ImageIO/ImageIO.h>

#import "CHTCollectionViewWaterfallLayout.h"
#define CELL_WIDTH 150.0
#define CELL_IDENTIFIER @"GCCategoryCell"
#import "CategoryCell.h"

@interface CategoryViewController () <UICollectionViewDataSource, CHTCollectionViewDelegateWaterfallLayout>
{
    NSMutableArray *cellHeights;
    NSMutableArray *arrCategory;
    UICollectionView *collectionView;
    CGFloat cellWidth;
}
@property (nonatomic, strong) NSMutableArray *cellHeights;
@property (nonatomic, strong) NSMutableArray * arrCategory;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic) CGFloat cellWidth;

@implementation CategoryViewController
@synthesize cellHeights;
@synthesize arrCategory;
@synthesize collectionView;

@synthesize cellWidth;

- (void)viewDidLoad
{
       self.arrCategory = [[NSMutableArray alloc] init];

        self.cellWidth = CELL_WIDTH;    // Default if not setting runtime attribute
        CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
        layout.sectionInset = UIEdgeInsetsMake(0.0, 10, 10, 5.0);
        layout.headerHeight = 0;
        layout.footerHeight = 0;
        if (IS_IPAD) {
            layout.minimumColumnSpacing = 30;
            layout.minimumInteritemSpacing = 30;
        }
        else
        {
            layout.minimumColumnSpacing = 5;
            layout.minimumInteritemSpacing = 5;
        }
        CGRect frame;
        if (IS_IPAD) {
            frame = CGRectMake(0, lblTitle.frame.size.height, self.view.frame.size.width, self.view.frame.size.height-36.0);
        }
        else
        {
            frame = CGRectMake(0, lblTitle.frame.size.height, self.view.frame.size.width, self.view.frame.size.height-(Appdel.objTab.frame.size.height + 36.0));
        }
        self.collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
        self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        self.collectionView.dataSource = self;
        self.collectionView.delegate = self;
        self.collectionView.backgroundColor = [UIColor clearColor];
        [self.collectionView registerClass:[GCCategoryCell class] forCellWithReuseIdentifier:CELL_IDENTIFIER];

        [self.view addSubview:self.collectionView];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self updateLayoutForOrientation:[UIApplication sharedApplication].statusBarOrientation];
}

#pragma mark --------------------------
#pragma mark Accessors
#pragma mark --------------------------

- (NSMutableArray *)cellHeights
{
    if (!cellHeights)
    {
        cellHeights = [[NSMutableArray alloc] init];
    }
    return cellHeights;
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                                         duration:(NSTimeInterval)duration {
    [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation
                                            duration:duration];
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"6.0")) {
        [self updateLayoutForOrientation:toInterfaceOrientation];
    }
}

- (void)updateLayoutForOrientation:(UIInterfaceOrientation)orientation
{
    CHTCollectionViewWaterfallLayout *layout = (CHTCollectionViewWaterfallLayout *)self.collectionView.collectionViewLayout;
    layout.columnCount = UIInterfaceOrientationIsPortrait(orientation) ? 2 : 3;
}

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

*** STEP 4:

// Call this method first to fill height array after you objects list
-(void)fillHeightArray
{
                for (NSMutableDictionary *dictGCCatInfo in self.arrCategory)
                {
                    NSNumber *width = [NSNumber numberWithFloat:200];
                    NSNumber *height = [NSNumber numberWithFloat:200];
                    
                    NSString *urlString = [dictGCCatInfo valueForKey:@"Photo"];
                    NSURL *imageFileURL = [NSURL URLWithString:urlString];
                    CGImageSourceRef imageSource = CGImageSourceCreateWithURL((__bridge CFURLRef)imageFileURL, NULL);
                    if (imageSource) {
                        NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:NO], (NSString *)kCGImageSourceShouldCache, nil];
                        CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, (__bridge CFDictionaryRef)options);
                        if (imageProperties) {
                            width = (NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);
                            height = (NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
                            CFRelease(imageProperties);
                        }
                    }
                    CFRelease(imageSource); // Added
                    CGSize size = CGSizeMake([width floatValue], [height floatValue]);
                    [self.cellHeights addObject:[NSValue valueWithCGSize:size]];
                }
[self.collectionView reloadData];
}

#pragma mark -----------------------------
#pragma mark UICollectionViewDataSource
#pragma mark -----------------------------

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [arrCategory count];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView1 cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CategoryCell *cell = (CategoryCell *)[collectionView1 dequeueReusableCellWithReuseIdentifier:CELL_IDENTIFIER
                                                                                       forIndexPath:indexPath];
    NSString *urlString = [[arrCategory objectAtIndex:indexPath.row] valueForKey:@"Photo"];
    if (urlString)
    {
        [cell.photoView setProcessedImage:nil];
        //set image
        [cell.photoView setImageWithContentsOfURL:[NSURL URLWithString:urlString]];
    }
    else
    {
        [cell.photoView setImage:[UIImage imageNamed:@"no-image.png"]];
    }
    [cell.photoView setTag:indexPath.row];
    [cell.btnPhoto setTag:indexPath.row];
    cell.titleLabel.text = [[arrCategory objectAtIndex:indexPath.row] valueForKey:@"GiftCertificateCatName"];
    [cell.btnPhoto addTarget:self action:@selector(btnCategoryClicked:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

#pragma mark ------------------------------------
#pragma mark CHTCollectionViewDelegateWaterfallLayout
#pragma mark ------------------------------------

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize size = [[self.cellHeights objectAtIndex:indexPath.row] CGSizeValue];
    return size;
}

Hope, you will fully enjoy this post about UICollectionView.

Best 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