How to add custom navigation bar (navigation bar with image)

Posted: Thursday, April 14, 2011 | Posted by Dipak Mishra | Labels: , 0 comments
A lot of time I came across a common problem of showing background image in navigation bar of iPhone application. For very first time, I used a very uncommon solution of inserting an image view in navigation bar. But then came other problem like showing title, left bar button and right bar button were getting hidden.

After a bit research I found a very easy solution of this problem. As a solution, we need to write few lines in Application's app delegate file and the navigation bar for that particular gets customized accordingly. Below is the code:
@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed: @"iphone_bar.jpg"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

If this piece of code solves you problem, do leave a comment below.

Enjoy!
Keep Reading...

Share

How to crop an image on iPhone

Posted: Friday, February 25, 2011 | Posted by Dipak Mishra | 3 comments

Here is a code for cropping image on iPhone.

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches]anyObject];
CGPoint loc = [touch locationInView:touch.view];

tmpVView.frame = CGRectMake(tmpVView.frame.origin.x, tmpVView.frame.origin.y, fabs(tmpVView.frame.origin.x-loc.x), fabs(tmpVView.frame.origin.y-loc.y));
}
-(void)cropImage:(id)sender
{
if(tmpVView && tmpVView.frame.size.width > 10 && tmpVView.frame.size.height > 10)
{
//UIImage *img = [originalImg.image imageScaledToSize:CGSizeMake(32.0f, 32.0f) interpolationQuality:1];
//UIImage *img = [self resizedImage:originalImg.image inFrame:originalImg.frame];
[originalImg drawRect:originalImg.frame];
finalImg.image = [self imageByCropping:originalImg.image toRect:tmpVView.frame];
[tmpVView removeFromSuperview];
[tmpVView release];
tmpVView = nil;
}
}
- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
//create a context to do our clipping in
UIGraphicsBeginImageContext(rect.size);
CGContextRef currentContext = UIGraphicsGetCurrentContext();

//create a rect with the size we want to crop the image to
//the X and Y here are zero so we start at the beginning of our
//newly created context
CGRect clippedRect = CGRectMake(0, 0, rect.size.width, rect.size.height);
CGContextClipToRect( currentContext, clippedRect);

//create a rect equivalent to the full size of the image
//offset the rect by the X and Y we want to start the crop
//from in order to cut off anything before them
CGRect drawRect = CGRectMake(rect.origin.x * -1,
rect.origin.y * -1,
imageToCrop.size.width,
imageToCrop.size.height);
CGContextTranslateCTM(currentContext, 0.0, drawRect.size.height);
CGContextScaleCTM(currentContext, 1.0, -1.0);
//draw the image to our clipped context using our offset rect
CGContextDrawImage(currentContext, drawRect, imageToCrop.CGImage);

//pull the image from our cropped context
UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();

//pop the context to get back to the default
UIGraphicsEndImageContext();

//Note: this is autoreleased
return cropped;
}

Enjoy!
Keep Reading...

Share

How to use iPhone contacts in your own application

Posted: Sunday, February 13, 2011 | Posted by Dipak Mishra | 0 comments
In this how to series, I have come up with yet another code snippet, which allows you to use iPhone’s contact data into your own application. The code is:

-(void)retrieveContactList
{
ABAddressBookRef myAddressBook = ABAddressBookCreate();
NSArray *allPeople = (NSArray *)ABAddressBookCopyArrayOfAllPeople(myAddressBook);
contactList = [[NSMutableArray alloc]initWithCapacity:[allPeople count]];
for (id record in allPeople) {
CFTypeRef phoneProperty = ABRecordCopyValue((ABRecordRef)record, kABPersonPhoneProperty);
NSArray *phones = (NSArray *)ABMultiValueCopyArrayOfAllValues(phoneProperty);
//NSLog(@”phones array: %@”, phones);
CFRelease(phoneProperty);
NSString* contactName = (NSString *)ABRecordCopyCompositeName((ABRecordRef)record);

NSMutableDictionary *newRecord = [[NSMutableDictionary alloc] init];
[newRecord setObject:contactName forKey:@"name"];
//[contactName release];
NSMutableString *newPhone = [[NSMutableString alloc] init];
for (NSString *phone in phones) {
//NSString *fieldData = [NSString stringWithFormat:@"%@: %@", contactName, phone];
if(![newPhone isEqualToString:@""])
[newPhone appendString:@", "];
[newPhone appendString:phone];

}
[newRecord setObject:newPhone forKey:@"phone"];
[newPhone release];
[phones release];
[contactList addObject:newRecord];
//[newPhone release];
}
CFRelease(myAddressBook);
// NSLog(@”Final data: %@”, contactList);
}

Enjoy!
Keep Reading...

Share

How to save current screen to iPhone library

Posted: Sunday, January 23, 2011 | Posted by Dipak Mishra | Labels: , 0 comments
Here is a quick post, in which I am posting a quick snippet to capture the current screen of iPhone and save it to the phone library. This piece of code will be helpful in generating screen-shot of any iPhone application programmatically.

  1. -(void)saveScreen
  2. {
  3. CGRect myRect = [self.view bounds];
  4. UIGraphicsBeginImageContext(myRect.size);
  5. CGContextRef ctx = UIGraphicsGetCurrentContext();
  6. [[UIColor blackColor] set];
  7. CGContextFillRect(ctx, myRect);
  8. [self.view.layer renderInContext:ctx];
  9. UIImage *image1 = UIGraphicsGetImageFromCurrentImageContext();
  10. UIImageWriteToSavedPhotosAlbum(image1, nil, nil, nil);
  11. UIGraphicsEndImageContext();
  12. }

Please leave your comments here so that I can find out, if you find this snippet useful or not

Enjoy!
Keep Reading...

Share

Using NSUserDefaults in iPhone app - Interesting fact.

Posted: Monday, November 1, 2010 | Posted by Dipak Mishra | Labels: , 0 comments
In one of my projects, I was using User Defaults for the first time. Then I came across a very interesting problem. I was writing this code for setting value to user defaults:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:@"Value" forKey:@"key"];

After setting the values this way, I tried retrieving the value for the key in next session, it simply did not return correct value.


After googling for a while, I came to know about this line and it worked perfectly:

[prefs synchronize];


Thus, I came to know that in order to use User Defaults, one have to use this synchronize function. The final code looks like:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:@"Value" forKey:@"key"];
[prefs synchronize];


Enjoy!
Keep Reading...

Share

Merging two images in objective-c

Posted: Thursday, October 28, 2010 | Posted by Dipak Mishra | Labels: , 0 comments
While researching about image manipulation for my next project, I came across an interesting piece of code, using which, we can merge two images into a single image. Here's the code:

-(UIImage*)mergeImage:(UIImage*)mask overImage:(UIImage*)source inSize:(CGSize)size
{
//Capture image context ref
UIGraphicsBeginImageContext(size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//Draw images onto the context
[source drawInRect:CGRectMake(0, 0, source.size.width, source.size.height)];
[mask drawInRect:CGRectMake(0, 0, mask.size.width, mask.size.height)];

return viewImage;

}


Got the reference from here.

Enjoy!
Keep Reading...

Share

Date formatting in Cocoa

Posted: Saturday, September 4, 2010 | Posted by Dipak Mishra | Labels: , 2 comments
"Date formatters format the textual representation of cells that contain date objects (including Gregorian dates), and convert textual representations of dates and times into date objects." - Apple Documentation.

While creating an app, you generally come across a situation, when you require custom date format to represent dates in user friendly manner. For this purpose, Cocoa provides date formatter class. Using a date formatter, we can express dates colloquially, such as “today,” “day after tomorrow,” and “a month from today.”

Here's the example of date formatter:
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]initWithDateFormat:@"%1m/%1d/%Y" allowNaturalLanguage:NO] autorelease];

NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:118800];


NSString *formattedDateString = [dateFormatter stringFromDate:date];


NSLog(@"formattedDateString: %@", formattedDateString);

// Output: formattedDateString: 1/2/2001


Below is the list of possible date conversions using date formatter (More detail on date conversion and range of conversions can be found here):

Specifier

Description

%%

A '%' character

%a

Abbreviated weekday name

%A

Full weekday name

%b

Abbreviated month name

%B

Full month name

%c

Shorthand for “%X %x", the locale format for date and time

%d

Day of the month as a decimal number (01-31)

%e

Same as %d but does not print the leading 0 for days 1 through 9 (unlike strftime(), does not print a leading space)

%F

Milliseconds as a decimal number (000-999)

%H

Hour based on a 24-hour clock as a decimal number (00-23)

%I

Hour based on a 12-hour clock as a decimal number (01-12)

%j

Day of the year as a decimal number (001-366)

%m

Month as a decimal number (01-12)

%M

Minute as a decimal number (00-59)

%p

AM/PM designation for the locale

%S

Second as a decimal number (00-59)

%w

Weekday as a decimal number (0-6), where Sunday is 0

%x

Date using the date representation for the locale, including the time zone (produces different results from strftime())

%X

Time using the time representation for the locale (produces different results from strftime())

%y

Year without century (00-99)

%Y

Year with century (such as 1990)

%Z

Time zone name (such as Pacific Daylight Time; produces different results from strftime())

%z

Time zone offset in hours and minutes from GMT (HHMM)



Hope this helps you in programming. Do let me know your views on it.

Enjoy Coding!
Keep Reading...

Share

How to show UIWebView without background

Posted: Sunday, August 29, 2010 | Posted by Dipak Mishra | Labels: , , 1 comments
I was working on an iPhone app, when I came across a problem, where I had to use UIWebView to show some of the data, but the background should not be shown (I had a background image for my app, and the content of web view should have to be shown just over the app background). But the background of web-view was showing as white color. After googling for sometime, I came across this small piece of code, which solved my problem:

[myWebView setBackgroundColor:[UIColor clearColor]];
[myWebView setOpaque:NO];
[myWebView loadHTMLString:@"<html>\
<body style="'background-color:transparent;'">\
Welcome!</body></html>";

And this small piece worked for me.


Enjoy!
Keep Reading...

Share

How to set specific year/month/date/time into UIDatePicker control

Posted: Sunday, August 15, 2010 | Posted by Dipak Mishra | Labels: , 0 comments
While working on a date picker control I encountered a problem, where I was supposed to set year of the date picker control to a specific year. For this problem, I added a custom text box over date picker. When a user enters a year in that text box and clicks done button, I changed the year of date picker to the year provided in text box.

Here is the piece of code, which I used to change year of my date picker control. This logic can be used to change other components of the date picker with any year, month or date.

Code:
NSDate *today=calenderPicker.date;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate: today];
components.year = [textField.text intValue]; // Here value for year is fetched from a text field control. Similarly other values like month, date, hour or minute can be changed.
[calenderPicker setDate: [gregorian dateFromComponents:components] ]; // Update the date picker control.
[gregorian release];



Enjoy!
Keep Reading...

Share

How to show UIPopover control with header bar and title

Posted: Sunday, August 8, 2010 | Posted by Dipak Mishra | Labels: , 0 comments
In iPad, we have a new control called UIPopover. This control shows up as an overlay in the screen with a UIViewController or UIView in it. But I came across a problem of showing title with header bar in Popover control. Then came across a set of solution, which solved my problem.

The logic behind this implementation is:
  • Create a view controller class (here demoViewController).
  • Create an object of navigation controller (here demoNavController) and initialize it with view controller as it's RootViewController.
  • Create an object of UIPopoverController (here demoPopup) and initialize it with navigation controller as it's ContentViewController
  • Set delegate of popover control to current class and set title of navigation controller with desired string.
  • Find bounds of a button (or any control, from where you want to present the popover control) and show the control from this bound.
And that's it.


Here is the code for this implementation:

if(trainnePopup == nil)
{
DemoViewController *demoViewController = [[DemoViewController alloc]initWithNibName:@"DemoViewController" bundle:[NSBundle mainBundle]];

UINavigationController *demoNavController = [[[UINavigationController alloc] initWithRootViewController:demoViewController] autorelease];

UIPopoverController *demoPopup = [[UIPopoverController alloc]initWithContentViewController:demoNavController];
[demoPopup setPopoverContentSize:CGSizeMake(demoViewController.view.frame.size.width, demoViewController.view.frame.size.height)];
[demoViewController release];
demoPopup.delegate = self;
demoPopup.contentViewController.title=@"Demo Popup";

}

// Below lines are used to show the arrow of the popover control
CGRect popoverRect= [self.view convertRect:[buttonCtrl bounds]
fromView:[buttonCtrl superview]];

[demoPopup presentPopoverFromRect:CGRectMake(335, 258, 100, 100)
inView:[self view] permittedArrowDirections: UIPopoverArrowDirectionUp
animated:YES];



Cheers!
Keep Reading...

Share