Wednesday, 1 October 2014

Set Multiple Images to ScrollView with PageControl

This is the code that I use when setting up a UIScrollView to contain multiple images that can be scrolled through. It has PageControl which shows no. of image as well.

Call this method from your Desired method (viewDidLoad or  viewWillAppear)

-(void) setupScrollView
 {
    //add the scrollview to the view

    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0,
                                                                     self.view.frame.size.width,
                                                                     self.view.frame.size.height)];
    self.scrollView.pagingEnabled = YES;

    [self.scrollView setAlwaysBounceVertical:NO];

    //setup internal views
    NSInteger numberOfViews = 3;

    for (int i = 0; i < numberOfViews; i++) 
{
        CGFloat xOrigin = i * self.view.frame.size.width;

        // add PageControl

        self.pageControl = [[UIPageControl alloc] init];

        self.pageControl.frame = CGRectMake(xOrigin+120, 175, 90, 37);

        self.pageControl.numberOfPages = 5;

        self.pageControl.pageIndicatorTintColor = [UIColor blackColor];

        self.pageControl.currentPageIndicatorTintColor = [UIColor greenColor];


        self.pageControl.currentPage = i;

        UIImageView *image = [[UIImageView alloc] initWithFrame:
                              CGRectMake(xOrigin, 0,
                                         self.view.frame.size.width,
                                         self.view.frame.size.height)];

       image.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",[imgArray objectAtIndex:i]]];      // imgArray is Array of Images

        image.contentMode = UIViewContentModeScaleToFill;

        [self.scrollView addSubview:image];
 }
    //set the scroll view content size
    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width *
                                             numberOfViews,
                                             self.view.frame.size.height);

    //add the scrollview to this view
    [self.view addSubview:self.scrollView];


}

Thanks & Regards
Angel AppTech

Send Email from iOS

To Send Email from iOS Application you must have to import MessageUI Framework to your application.

To add this Framework Select -> Target -> Build Phases -> Link Binary with Libraries
Now import Framework in your file.


Next, click "+" button and select "MessageUI Framework" and click the Add button. After you click the Add button Framework will be added to your application. 



#import <MessageUI/MessageUI.h>

Add MFMailComposeDelegate 

@interface ViewController : UIViewController<MFMailComposeViewControllerDelegate

Now write below code to send mail from our app. here I have added one button named "Send Email"and connected my below method to it to send the mail. You can put this code from where ever you wants to send mail.

- (IBAction)sendEmail:(id)sender
{
    // Email Subject
    NSString *emailTitle = @"Test mail";
    // Email Content
    NSString *messageBody = @"It is Mail for testing!";
    // To address
    NSArray *toRecipents = [NSArray arrayWithObject:@"ios@gmail.com"];
    
    MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
    mc.mailComposeDelegate = self;
    [mc setSubject:emailTitle];
    [mc setMessageBody:messageBody isHTML:NO];
    [mc setToRecipients:toRecipents];
    
    // Present mail view controller on screen
    [self presentViewController:mc animated:YES completion:NULL];
    
}

This is Delegate method of MFMailComposeViewController. This method will be called automatically when the mail interface is closed. (e.g. user cancel the operation or mail sent)

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail sent");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail sent failure: %@", [error localizedDescription]);
            break;
        default:
            break;
    }
    
    // Close the Mail Interface
    [self dismissViewControllerAnimated:YES completion:NULL];

}


Build and Run and you will see just like that


Thanks & Regards
Angel AppTech



Set Textview Text in Center Vertically and Horizontally


To make the textview text horizontally center, select the textview from .xib class and go to the library and in that set Alignment as center.

But it is not easy to set is in centre for both vertically and Horizontally. 
but we can do it by observing the contentsize of UITextView, when there is any change in the contentSize, update the contentOffset.

Add observer as follows in viewDidLoad or viewWillAppear

[textview addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];

Handle the observer action as follows:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 
{
     UITextView *txtview = object;
     CGFloat topoffset = ([txtview bounds].size.height - [txtview contentSize].height * [txtview zoomScale])/2.0;
     topoffset = ( topoffset < 0.0 ? 0.0 : topoffset );
     txtview.contentOffset = (CGPoint){.x = 0, .y = -topoffset};
}

Remove observer in viewDidUnLoad or viewWillDisappear depends on where you add

[textview removeObserver:self forKeyPath:@"contentSize" context:NULL];


Thanks & Regards
Angel AppTech

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