Tuesday, 30 September 2014

Add UIPanGestureRecognizer to View

Adding PanGestureRecognizer to your view its very easy.

Here i have added PanGestureRecognizer to ImageView. so i can move my imageview in my view.

Add following code to any method to add PanGestureRecognizer to your view. i added this to ViewWillAppear.


-(void)viewWillAppear:(BOOL)animated
{
         UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];

          [panRecognizer setMinimumNumberOfTouches:1];

          [panRecognizer setMaximumNumberOfTouches:1];

          [ViewMain addGestureRecognizer:panRecognizer];

          [panRecognizer release];
}
- (Void)handlePan:(UIPanGestureRecognizer *)recognizer
    {
   
         CGPoint translation = [recognizer translationInView:self.view];
         recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                         recognizer.view.center.y + translation.y);
         [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
     
         if (recognizer.state == UIGestureRecognizerStateEnded) {
       
             CGPoint velocity = [recognizer velocityInView:self.view];
             CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
            CGFloat slideMult = magnitude / 200;
            NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);
       
            float slideFactor = 0.1 * slideMult; // Increase for more of a slide
            CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor),
                                         recognizer.view.center.y + (velocity.y * slideFactor));
        finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);
        finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);
       
        [UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            recognizer.view.center = finalPoint;
        } completion:nil];
       
    }
   
    }


Thanks & Regards
Angel AppTech

Add Controls Programatically

It is very easy to Add Controls programmatically we just need to set the frames of controls as per our requirements.

In this post i have added UIView, UIImageView, UILabel, UIButton and UITextField.

- (void)viewDidLoad
{
        [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    
    UIView *dynamicView=[[UIView alloc]initWithFrame:CGRectMake(10, 15, 300, 500)];
    [dynamicView setBackgroundColor:[UIColor grayColor]];
    [self.view addSubview:dynamicView];
    
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 20, 140, 150)];
    [imageView setImage:[UIImage imageNamed:@"audi.png"]];
    [dynamicView addSubview:imageView];
    
    UIImageView *imageView2=[[UIImageView alloc]initWithFrame:CGRectMake(160, 20, 140, 150)];
    [imageView2 setImage:[UIImage imageNamed:@"bmw.png"]];
    [dynamicView addSubview:imageView2];
    
    UILabel *label1=[[UILabel alloc]initWithFrame:CGRectMake(60, 180, 50, 20)];
    [label1 setBackgroundColor:[UIColor clearColor]];
    [label1 setText:@"Audi"];
    [label1 setTextAlignment:UITextAlignmentCenter];
    [label1 setFont:[UIFont systemFontOfSize:20.0f]];
    [dynamicView addSubview:label1];
    
    UILabel *label2=[[UILabel alloc]initWithFrame:CGRectMake(200, 180, 50, 20)];
    [label2 setBackgroundColor:[UIColor clearColor]];
    [label2 setText:@"BMW"];
    [label2 setTextAlignment:UITextAlignmentCenter];
    [label2 setFont:[UIFont systemFontOfSize:20.0f]];
    [dynamicView addSubview:label2];
    
    
    UITextField *textfield=[[UITextField alloc]initWithFrame:CGRectMake(10, 250, 120, 30)];
    [textfield setBorderStyle:UITextBorderStyleRoundedRect];
    [textfield setText:@"Demo Text"];
    [dynamicView addSubview:textfield];
    
    UIButton *dynamicButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [dynamicButton setFrame:CGRectMake(200, 250, 80, 30)];
    [dynamicButton setTitle:@"Click Me" forState:UIControlStateNormal];
    [dynamicButton addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
    [dynamicView addSubview:dynamicButton];

}

// Method for button 

-(IBAction)buttonClicked;
{
    NSLog(@"Button Clicke Event Called");

}


Thanks & Regards
Angel AppTech

Import Contacts Into Application

First you have to include "AddressBookUI.framework" into your project and then you have to  include "UINavigationControllerDelegate", "ABPeoplePickerNavigationControllerDelegate" into header part of the controller. 

You have to also import "#import <AddressBookUI/AddressBookUI.h>" into current controller's header part. 

#import <AddressBookUI/AddressBookUI.h>

@interface ViewController :  UIViewController<UINavigationControllerDelegate,ABPeoplePickerNavigationControllerDelegate>

Declare one method to pick up contacts

-(IBAction)callAddressbook:(id)sender;

Make Connection of this method with your button.

Declare two objects in your interface section. one Array object to store the contact information.

@property (nonatomic, strong) NSMutableArray *arrContactsData;

@property (nonatomic, strong) ABPeoplePickerNavigationController *addressBookController;

Now put the following code in your button's event. it will open your contacts list

-(IBAction)callAddressbook:(id)sender
{
    _addressBookController = [[ABPeoplePickerNavigationController alloc] init];
    [_addressBookController setPeoplePickerDelegate:self];
    [self presentViewController:_addressBookController animated:YES completion:nil];


}

Now we will call Delagate methods of ABPeoplePickerNavigationController

#pragma mark -
#pragma mark ABPeoplePickerNavigationController Delegate Method

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker // called when address book closed
{
    [peoplePicker dismissModalViewControllerAnimated:YES];
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker  // called when select any contact from address book
      shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
    
    // Initialize a mutable dictionary and give it initial values.
    NSMutableDictionary *contactInfoDict = [[NSMutableDictionary alloc]
                                            initWithObjects:@[@"", @"", @"", @"", @"", @"", @"", @"", @"",@""]
                                            forKeys:@[@"firstName", @"lastName", @"mobileNumber", @"homeNumber", @"homeEmail", @"workEmail", @"address", @"zipCode", @"city",@"birthDate"]];
    
    // Use a general Core Foundation object.
    CFTypeRef generalCFObject = ABRecordCopyValue(person, kABPersonFirstNameProperty);
    
    // Get the first name.
    if (generalCFObject)
 {
        [contactInfoDict setObject:(__bridge NSString *)generalCFObject forKey:@"firstName"];
        CFRelease(generalCFObject);
 }
    
    // Get the last name.
    generalCFObject = ABRecordCopyValue(person, kABPersonLastNameProperty);

    if (generalCFObject) {
        [contactInfoDict setObject:(__bridge NSString *)generalCFObject forKey:@"lastName"];
        CFRelease(generalCFObject);
    }
    
    // Get the phone numbers as a multi-value property.

    ABMultiValueRef phonesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);

    for (int i=0; i<ABMultiValueGetCount(phonesRef); i++)
 {
        CFStringRef currentPhoneLabel = ABMultiValueCopyLabelAtIndex(phonesRef, i);
        CFStringRef currentPhoneValue = ABMultiValueCopyValueAtIndex(phonesRef, i);
        
        if (CFStringCompare(currentPhoneLabel, kABPersonPhoneMobileLabel, 0) == kCFCompareEqualTo)
    {
            [contactInfoDict setObject:(__bridge NSString *)currentPhoneValue forKey:@"mobileNumber"];
    }
        
    if (CFStringCompare(currentPhoneLabel, kABHomeLabel, 0) == kCFCompareEqualTo)
   {
            [contactInfoDict setObject:(__bridge NSString *)currentPhoneValue forKey:@"homeNumber"]
   }
        
        CFRelease(currentPhoneLabel);
        CFRelease(currentPhoneValue);
    }
    CFRelease(phonesRef);
    
    
    // Get the e-mail addresses as a multi-value property.

    ABMultiValueRef emailsRef = ABRecordCopyValue(person, kABPersonEmailProperty);

    for (int i=0; i<ABMultiValueGetCount(emailsRef); i++)
  {
        CFStringRef currentEmailLabel = ABMultiValueCopyLabelAtIndex(emailsRef, i);
        CFStringRef currentEmailValue = ABMultiValueCopyValueAtIndex(emailsRef, i);
        
        if (CFStringCompare(currentEmailLabel, kABHomeLabel, 0) == kCFCompareEqualTo)
       {
            [contactInfoDict setObject:(__bridge NSString *)currentEmailValue forKey:@"homeEmail"];
        }
        
        if (CFStringCompare(currentEmailLabel, kABWorkLabel, 0) == kCFCompareEqualTo)
      {
            [contactInfoDict setObject:(__bridge NSString *)currentEmailValue forKey:@"workEmail"];
      }
        
        CFRelease(currentEmailLabel);
        CFRelease(currentEmailValue);
    }
    CFRelease(emailsRef);
    
    
    // Use a general Core Foundation object for fetching Birth Date.

    CFTypeRef generalObject = ABRecordCopyValue(person, kABPersonBirthdayProperty);
    
    if (generalCFObject)
    {
        [contactInfoDict setObject:(__bridge NSString *)generalObject forKey:@"birthDate"];
        CFRelease(generalCFObject);
    }
    
    // Get the first street address among all addresses of the selected contact.

    ABMultiValueRef addressRef = ABRecordCopyValue(person, kABPersonAddressProperty);

    if (ABMultiValueGetCount(addressRef) > 0)
  {
        NSDictionary *addressDict = (__bridge NSDictionary *)ABMultiValueCopyValueAtIndex(addressRef, 0);
        
        [contactInfoDict setObject:[addressDict objectForKey:(NSString *)kABPersonAddressStreetKey] forKey:@"address"];
        [contactInfoDict setObject:[addressDict objectForKey:(NSString *)kABPersonAddressZIPKey] forKey:@"zipCode"];
        [contactInfoDict setObject:[addressDict objectForKey:(NSString *)kABPersonAddressCityKey] forKey:@"city"];
    }
    CFRelease(addressRef);
    
    
    // If the contact has an image then get it too.

    if (ABPersonHasImageData(person))
   {
        NSData *contactImageData = (__bridge NSData *)ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail);
        
        [contactInfoDict setObject:contactImageData forKey:@"image"];
    }
    
    // Initialize the array if it's not yet initialized.

    if (_arrContactsData == nil) {
        _arrContactsData = [[NSMutableArray alloc] init];
    }
    // Add the dictionary to the array.
    [_arrContactsData addObject:contactInfoDict];
    
    // Reload the table view data.
    //[self.tableView reloadData];
    
    // Dismiss the address book view controller.

    [_addressBookController dismissViewControllerAnimated:YES completion:nil];
    
    NSLog(@"Contact details is : %@",contactInfoDict);
    
    return NO;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker
      shouldContinueAfterSelectingPerson:(ABRecordRef)person
                                property:(ABPropertyID)property
                              identifier:(ABMultiValueIdentifier)identifier // called to show detail of contact
{
    return NO;

}

Finished now build Run your code now and click on your button your contacts list will be open


Click on any contact and all details of that contact will be store in contactInfoDict,


Thanks & Regards
Angel AppTech

Save and Retrieve data from NSUserDefaults

 NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];  

Set values to userDefaults 

 [userDefaults setBool:YES forKey:@"keyForBOOL"];  
 [userDefaults setDouble:10.5454 forKey:@"keyForDouble"];  
 [userDefaults setFloat:10.5 forKey:@"keyForFloat"];  
 [userDefaults setInteger:10 forKey:@"keyForInteger"];  
 [userDefaults setURL:[NSURL URLWithString:@"http://nsuserdefaults-in-iphone-sdk.blogspot.in/"]forKey:@"keyForURL"];  
 [userDefaults setObject:@"Hello" forKey:@"keyForObject"];  

 [userDefaults synchronize];  


Thats all. all your values will be stored in your userDefaults.
Get Values from userDefaults.


 NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];  


 BOOL isYou = [userDefaults boolForKey:@"keyForBOOL"];  
 double varDouble = [userDefaults doubleForKey:@"keyForDouble"];  
 float varFloat = [userDefaults floatForKey:@"keyForFloat"];  
 NSInteger varInt = [userDefaults integerForKey:@"keyForInteger"];  
 NSURL *url = [userDefaults URLForKey:@"keyForURL"];  

 NSString *str = [userDefaults objectForKey:@"keyForObject"];  


Thanks & Regards
Angel AppTech

Add -ObjC to the Other Linker Flag in xCode


You should be able to click to the right of Other Linker Flags(under build settings) and add it. This image shows how it goes.



Thanks & Regards
Angel AppTech

Disable ARC for a single file in a project?

It is possible to disable ARC for individual files by adding the -fno-objc-arc compiler flag for those files.


You add compiler flags in Targets -> Build Phases -> Compile Sources. You have to double click on the right column of the row under Compiler Flags. You can also add it to multiple files by holding the cmd button to select the files and then pressing enter to bring up the flag edit box.






Thanks & Regards
 Angel AppTech

Change UITableView Cell Selection Color

You can change the highlight Color in several ways.
  1. Change the selectionStyle property of your cell to UITableViewCellSelectionStyleGray. If you change it to , it will be gray.
  2. Change the selectedBackgroundView property. Actually what creates the blue gradient is a view. You can create a view and draw what ever Color you like, and use the view as the background of your table view cells.
  3. You can also set None UITableViewCellSelectionStyleNone to it. that means there will be no Selection Style.

Write below code into -(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

This is to make it gray.

if(cell == nil)
{
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
}



This code is for setting your choice color

if(cell == nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.backgroundColor = [UIColor clearColor];
        
        UIView *bgColorView = [[UIView alloc] init];
        bgColorView.backgroundColor = [UIColor greenColor];
        [cell setSelectedBackgroundView:bgColorView];


    }




You can also set RGB color to it just like below code.

if(cell == nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.backgroundColor = [UIColor clearColor];
        
        UIView *bgColorView = [[UIView alloc] init];
        bgColorView.backgroundColor = [UIColor colorWithRed:255.0/256.0 green:139.0/256.0 blue:15.0/256.0 alpha:1];
        [cell setSelectedBackgroundView:bgColorView];
    }


                                                                                                                                                                     
Thanks & Regards
 Angel AppTech