0

Some iOS development tricks

-

1. How to create transparent UIBarButtonItem

  1. UIImage *reloadImage = [UIImageimageNamed:@"refresh_button88.png"];
  2. UIButton *reloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
  3. [reloadButton setBackgroundImage:reloadImage forState:UIControlStateNormal];
  4. [reloadButton setFrame:CGRectMake(0, 0, 44, 44)];
  5. UIBarButtonItem *reloadBarButton = [[UIBarButtonItemalloc] initWithCustomView:reloadButton];
  6.  
  7. self.navigationItemsetLeftBarButtonItem:reloadBarButton];
UIImage *reloadImage = [UIImageimageNamed:@"refresh_button88.png"];
UIButton *reloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
[reloadButton setBackgroundImage:reloadImage forState:UIControlStateNormal]; 
[reloadButton setFrame:CGRectMake(0, 0, 44, 44)];
UIBarButtonItem *reloadBarButton = [[UIBarButtonItemalloc] initWithCustomView:reloadButton];

self.navigationItemsetLeftBarButtonItem:reloadBarButton];

2. How to display transparent image in UIBarButtonItem

  1. UIImageView *brosurkuLogo = [[UIImageViewalloc] initWithImage:[UIImageimageNamed:@"brosurku.jpg"]];
  2. [brosurkuLogo setFrame:CGRectMake(0, 0, 64, 36)];
  3. UIBarButtonItem *brosurkuBarButton = [[UIBarButtonItemalloc] initWithCustomView:brosurkuLogo];
  4. [self.navigationItemsetRightBarButtonItem:brosurkuBarButton];
UIImageView *brosurkuLogo = [[UIImageViewalloc] initWithImage:[UIImageimageNamed:@"brosurku.jpg"]];
[brosurkuLogo setFrame:CGRectMake(0, 0, 64, 36)];
UIBarButtonItem *brosurkuBarButton = [[UIBarButtonItemalloc] initWithCustomView:brosurkuLogo];
[self.navigationItemsetRightBarButtonItem:brosurkuBarButton];

3. How to change background on UINavigationBar

  1. [navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"header_bar.png"] forBarMetrics:UIBarMetricsDefault];
[navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"header_bar.png"] forBarMetrics:UIBarMetricsDefault];

4. How to change statusbar color

  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  2. {
  3. [application setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:NO];
  4. }
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[application setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:NO];
}

5. How to change window pattern

  1. + (UIWindow *) customizeWindow: (UIWindow *) window withTexture: (NSString *) filename {
  2. [window setBackgroundColor: [UIColor colorWithPatternImage: [UIImage imageNamed: filename]]];
  3. return window;
  4. }
+ (UIWindow *) customizeWindow: (UIWindow *) window withTexture: (NSString *) filename {
[window setBackgroundColor: [UIColor colorWithPatternImage: [UIImage imageNamed: filename]]];
return window;
}

6. How to create custom searchbar

  1. searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
  2. [searchBar setPlaceholder:@"Search in Plaza Lapiazza, Jakarta Raya, Indonesia"];
  3.  
  4. //to remove searchbar default background layer
  5. if ([[[searchBar subviews] objectAtIndex:0] isKindOfClass:[UIImageViewclass]]){
  6. [[[searchBar subviews] objectAtIndex:0] removeFromSuperview];
  7. }
  8.  
  9. //to remove search icon. Note that objectAtIndex = 0 because background layer is already removed
  10. UITextField *textField;
  11. if ([[[searchBar subviews] objectAtIndex:0] isKindOfClass:[UITextFieldclass]]){
  12. textField = [[searchBarsubviews] objectAtIndex:0];
  13. }
  14. textField.leftView = nil;
  15.  
  16. //to change textField frame
  17. UIImage *searchBarImage = [[UIImage imageNamed:@"search_bar_fit.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 10, 0, 10)];
  18. [textField setBackground:searchBarImage];
  19.  
  20. //to change textfield font and size
  21. [textField setFont:[UIFontfontWithName:@"HelveticaNeue-Light" size:15]];\
  22.  
  23. //to add transparent background on searchbar
  24. [searchBar setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"search_bottom.png"]]];
  25. [[searchBar layer] setOpaque:NO];
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[searchBar setPlaceholder:@"Search in Plaza Lapiazza, Jakarta Raya, Indonesia"];

//to remove searchbar default background layer
if ([[[searchBar subviews] objectAtIndex:0] isKindOfClass:[UIImageViewclass]]){
[[[searchBar subviews] objectAtIndex:0] removeFromSuperview];
}

//to remove search icon. Note that objectAtIndex = 0 because background layer is already removed
UITextField *textField;
if ([[[searchBar subviews] objectAtIndex:0] isKindOfClass:[UITextFieldclass]]){
textField = [[searchBarsubviews] objectAtIndex:0];
}
textField.leftView = nil;

//to change textField frame
UIImage *searchBarImage = [[UIImage imageNamed:@"search_bar_fit.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 10, 0, 10)];
[textField setBackground:searchBarImage];

//to change textfield font and size
[textField setFont:[UIFontfontWithName:@"HelveticaNeue-Light" size:15]];\

//to add transparent background on searchbar
[searchBar setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"search_bottom.png"]]];
[[searchBar layer] setOpaque:NO];

7. How to add toolbar

  1. //create button with custom font
  2. UIButton *categoryButton = [UIButton buttonWithType:UIButtonTypeCustom];
  3. [categoryButton setFrame:CGRectMake(10, 0, 300, 44)];
  4. [categoryButton.titleLabel setFont:[UIFontfontWithName:@"HelveticaNeue-Bold" size:15]];
  5. [categoryButton setTitle:@"CATEGORY" forState:UIControlStateNormal];
  6. [categoryButton addTarget:self action:@selector(toggleCategory) forControlEvents:UIControlEventTouchDown];
  7.  
  8. //to add item in toolbar in this viewcontroller
  9. UIBarButtonItem *toolBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:categoryButton];
  10. [selfsetToolbarItems:[NSArray arrayWithObject:toolBarButtonItem]];
  11.  
  12. //to display toolbar with custom height
  13. //you must called these two method in viewWillAppear and viewWillDisappear if you only want to display in some view controller only
  14. [self.navigationController setToolbarHidden:YES animated:YES];
  15.  
  16. [self.navigationController.toolbarsetFrame:CGRectMake(0, 450, 320, 30)];
  17.  
  18. //to display toolbar in some view controller only
  19. - (void)viewWillAppear:(BOOL)animated{
  20. [super viewWillAppear:animated];
  21. [self.navigationController setToolbarHidden:NOanimated:YES];
  22. [self.navigationController.toolbarsetFrame:CGRectMake(0, 450, 320, 30)];
  23. }
  24.  
  25. - (void)viewWillDisappear:(BOOL)animated{
  26. [super viewWillDisappear:animated];
  27. [self.navigationController setToolbarHidden:YESanimated:YES];
  28. }
//create button with custom font
UIButton *categoryButton = [UIButton buttonWithType:UIButtonTypeCustom];
[categoryButton setFrame:CGRectMake(10, 0, 300, 44)];
[categoryButton.titleLabel setFont:[UIFontfontWithName:@"HelveticaNeue-Bold" size:15]];
[categoryButton setTitle:@"CATEGORY" forState:UIControlStateNormal];
[categoryButton addTarget:self action:@selector(toggleCategory) forControlEvents:UIControlEventTouchDown];

//to add item in toolbar in this viewcontroller
UIBarButtonItem *toolBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:categoryButton];
[selfsetToolbarItems:[NSArray arrayWithObject:toolBarButtonItem]];

//to display toolbar with custom height
//you must called these two method in viewWillAppear and viewWillDisappear if you only want to display in some view controller only
[self.navigationController setToolbarHidden:YES animated:YES];

[self.navigationController.toolbarsetFrame:CGRectMake(0, 450, 320, 30)];

//to display toolbar in some view controller only
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.navigationController setToolbarHidden:NOanimated:YES];
[self.navigationController.toolbarsetFrame:CGRectMake(0, 450, 320, 30)];
}

- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[self.navigationController setToolbarHidden:YESanimated:YES];
}

8. How to change barStyle to black

  1. [navigationController.toolbar setBarStyle:UIBarStyleBlackOpaque];
  2. [navigationController.navigationBar setBarStyle:UIBarStyleBlackOpaque];
[navigationController.toolbar setBarStyle:UIBarStyleBlackOpaque];
[navigationController.navigationBar setBarStyle:UIBarStyleBlackOpaque];

9. How to create button with custom font

  1. //create button with custom font
  2. //titleLabel is read only property, however you can still set font, shadowOffset, and lineBreakMode
  3. UIButton *categoryButton = [UIButtonbuttonWithType:UIButtonTypeCustom];
  4. [categoryButton setFrame:CGRectMake(10, 0, 300, 44)];
  5. [categoryButton.titleLabel setFont:[UIFontfontWithName:@"HelveticaNeue-Bold" size:15]];
  6. [categoryButton setTitle:@"CATEGORY" forState:UIControlStateNormal];
  7. [categoryButton addTarget:selfaction:@selector(toggleCategory) forControlEvents:UIControlEventTouchDown];
//create button with custom font
//titleLabel is read only property, however you can still set font, shadowOffset, and lineBreakMode
UIButton *categoryButton = [UIButtonbuttonWithType:UIButtonTypeCustom];
[categoryButton setFrame:CGRectMake(10, 0, 300, 44)];
[categoryButton.titleLabel setFont:[UIFontfontWithName:@"HelveticaNeue-Bold" size:15]];
[categoryButton setTitle:@"CATEGORY" forState:UIControlStateNormal];
[categoryButton addTarget:selfaction:@selector(toggleCategory) forControlEvents:UIControlEventTouchDown];
4

Simplifying Facebook iOS SDK

-

The Problem with Facebook iOS SDK

Facebook+Singleton
Now that the Facebook iOS SDK has been changed to use Graph API, many people are trying to figure out just how to use it properly. In my opinion, however, there are problems with the SDK’s architecture that make it likely to be used poorly. For example, Facebook’s documentationrecommends instantiating the Facebook class and authenticating from within your AppDelegate. This is suboptimal for a several of reasons.

First, in many apps that allow Facebook integration, the user may never actually use the Facebook features. Thus, loading the class and authenticating the user is something that should only be done when the user has decided to use a Facebook feature. In other words, we should be lazy loading the Facebook class but their documentation suggests otherwise.

Secondly, the log in method chosen by Facebook (fast-switching the user to the Facebook app or Safari to log in) makes a very poor first impression for your app. Who wants their app to look like it crashed then loaded some Web page the very first time it’s launched?

(more...)

0

iOS Code: MKiCloudSync – Sync your NSUserDefaults to iCloud with a single line of code

-

Just wrote this class, MKiCloudSync (100 lines of code) that auto syncs your NSUserDefaults to iCloud.

How to use?

All you need to do is to enable iCloud key value store entitlements, copy the files and forget about the rest.

Step 1:

Enable iCloud entitlements for your app. This is easily done in Xcode 4.2.1 by opening your target settings and checking “Enable Entitlements” from the summary tab.

This is illustrated below.

Xcode

Enabling iCloud Entitlements in Xcode 4.2.1
Tip:
If you are sharing settings with other apps, ensure that your iCloud Key-Value Store is the same across all those apps.
Step 2:
Drag the two files

  • MKiCloudSync.h
  • MKiCloudSync.m

into your project. You can find these files in the Source Code section of this post.
Step 3:
In your applicationDidFinishLaunchingWithOptions: method,
start the sync by calling,

  1. [MKiCloudSync start];
[MKiCloudSync start];

You also have to #include the header file.
This is probably the only line of code you have to write!
Step 4:
Sleep… Kidding.

There is no step 4. Continue using NSUserDefaults to save your settings. The MKiCloudSync class automatically syncs your settings to iCloud and restores them back to your NSUserDefaults when they are changed on other devices.

To top them all, it also posts a notification,

  1. kMKiCloudSyncNotification
kMKiCloudSyncNotification

to let you know that a sync has been performed. You can listen to this notification and update your user interface from NSUserDefaults.

Advantages

  • Upgrading your existing iOS 4 apps to sync settings to iCloud is now super easy.
  • With this class, you no longer have to add calls to NSUbiquitousKeyValueStore throughout your app. You can continue your existing method of saving them to NSUserDefaults. Everything is automatic. If your settings might change often, you can observe the notification kMKiCloudSyncNotification and update your user interface.

Source Code

Licensing

Royalty free for commercial or non-commercial use, though attribution will please me to write more such code :)

iOS Code: MKiCloudSync – Sync your NSUserDefaults to iCloud with a single line of code | MKBlog.

1

UIDeviceHardware Helper

-

feel free to use this class

Usage

  1. <code>UIDeviceHardware *h=[[UIDeviceHardware alloc] init];
  2. [self setDeviceModel:[h platformString]];  
  3. [h release];
  4. </code>
<code>UIDeviceHardware *h=[[UIDeviceHardware alloc] init];
[self setDeviceModel:[h platformString]];   
[h release];
</code>

UIDeviceHardware.h

  1. <code>//
  2. //  UIDeviceHardware.h
  3. //
  4. //  Used to determine EXACT version of device software is running on.
  5.  
  6. #import <Foundation/Foundation.h>
  7.  
  8. @interface UIDeviceHardware : NSObject
  9.  
  10. - (NSString *) platform;
  11. - (NSString *) platformString;
  12.  
  13. @end
  14. </code>
<code>//
//  UIDeviceHardware.h
//
//  Used to determine EXACT version of device software is running on.

#import <Foundation/Foundation.h>

@interface UIDeviceHardware : NSObject 

- (NSString *) platform;
- (NSString *) platformString;

@end
</code>

UIDeviceHardware.m

  1. <code>//
  2. //  UIDeviceHardware.m
  3. //
  4. //  Used to determine EXACT version of device software is running on.
  5.  
  6. #import "UIDeviceHardware.h"
  7. #include <sys/types.h>
  8. #include <sys/sysctl.h>
  9.  
  10. @implementation UIDeviceHardware
  11.  
  12. - (NSString *) platform{
  13.     size_t size;
  14.     sysctlbyname("hw.machine", NULL, &size, NULL, 0);
  15.     char *machine = malloc(size);
  16.     sysctlbyname("hw.machine", machine, &size, NULL, 0);
  17.     NSString *platform = [NSString stringWithCString:machine];
  18.     free(machine);
  19.     return platform;
  20. }
  21.  
  22. - (NSString *) platformString{
  23.     NSString *platform = [self platform];
  24.     if ([platform isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
  25.     if ([platform isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
  26.     if ([platform isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
  27.     if ([platform isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
  28.     if ([platform isEqualToString:@"iPhone3,3"])    return @"Verizon iPhone 4";
  29.     if ([platform isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
  30.     if ([platform isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
  31.     if ([platform isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
  32.     if ([platform isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
  33.     if ([platform isEqualToString:@"iPad1,1"])      return @"iPad";
  34.     if ([platform isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
  35.     if ([platform isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
  36.     if ([platform isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
  37.     if ([platform isEqualToString:@"i386"])         return @"Simulator";
  38.     return platform;
  39. }
  40.  
  41. @end
  42. </code>
<code>//
//  UIDeviceHardware.m
//
//  Used to determine EXACT version of device software is running on.

#import "UIDeviceHardware.h"
#include <sys/types.h>
#include <sys/sysctl.h>

@implementation UIDeviceHardware

- (NSString *) platform{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine];
    free(machine);
    return platform;
}

- (NSString *) platformString{
    NSString *platform = [self platform];
    if ([platform isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([platform isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,3"])    return @"Verizon iPhone 4";
    if ([platform isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([platform isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([platform isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([platform isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([platform isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([platform isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([platform isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    if ([platform isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([platform isEqualToString:@"i386"])         return @"Simulator";
    return platform;
}

@end
</code>

UPDATE (01/14/11)

Obviously, this code is a bit out of date by now, but it can certainly be updated using the code on this thread provided by Brian Robbins which includes similar code with updated models. Thanks for the support on this thread.

 

0

UITextField – A Complete API Overview

-

The UITextField is probably one of the most commonly used UI controls on the iPhone. It is the primary method of user input via the keyboard and provides a great deal of additional functionality.

With the success of our las API tutorial on NSArray, I thought I would do another walkthrough, this time on UITextField. I will be explaining all of the properties for it as well as bringing up some functionality that you may not have known about.

Text Attributes

The attributes have to do with the actual text inside of the UITextField.

text The text displayed in the UITextField
placeholder The text that gets displayed prior to the user entering in anything. This text is usually a lighter color than the primary text to denote that it will be replaced.
font The font of the text to be displayed. You can set it like this
textColor The color of the text that is displayed
textAlignment How the text is aligned in the UITextField. The possible values for this are UITextAlignmentLeft, UITextAlignmentRight, UITextAlignmentCenter

Here are some examples of using these properties.

// Setting the text
[myTextField setText:@"This is some text!"];

// Setting the placeholder
[myTextField setPlaceholder:@"Type text here"];

// Setting the font.
[myTextField setFont:[UIFont fontWithName:@"Times New Roman" size:14]];

// Setting the text color
[myTextField setTextColor:[UIColor blueColor]];

// Setting the text alignment
[myTextField setTextAlignment:UITextAlignmentCenter];

Here is what the UITextField would look like after we update these properties.

Adjusting the size of the text in the UITextField

The text displayed in our UITextField can be dynamically sized based on the width of the UITextField. The benefit of this is all of the text being typed will be visible on the screen. It will shrink the text down until it reaches the default font size of 17. So, for this to make sense, you must set the font size of the UITextField to something larger than 17.

adjustsFontSizeToFitWidth Boolean value denoting whether to fit the font size to the width of the UITextField.

Here is an example of using these properties.

[myTextField setFont:[UIFont fontWithName:@"Times New Roman" size:30]];
[myTextField setAdjustsFontSizeToFitWidth:YES];

Here are some screenshots of the text shrinking when typing in the UITextField.

Managing the editor’s behavior

These two properties are pretty straight forward.

editing Read-only boolean value letting you know if the user is currently editing the UITextField
clearsOnBeginEditing Clears the text in the field every time the user begins to edit it.

Not very exciting and probably doesn’t even deserve an example…

Setting the view’s background appearance

This group of properties defines how the UITextField will look. If you have ever seen a fancy input box, this is how they are doing it.

borderStyle Defines the type of border for the UITextField. Possible choices are UITextBorderStyleNone, UITextBorderStyleLine, UITextBorderStyleBezel, and UITextBorderStyleRoundedRect. The default is UITextBorderStyleNone.
background A UIImage representing the background image of the UITextField when it’s enabled. If this field is altered the borderStyle property is ignored.
backgroundDisabled A UIImage representing the background image of the UITextField when it’s disabled.

Here is are some example of using each of the border styles

// Border Style None
[myTextField setBorderStyle:UITextBorderStyleNone];

// Border Style Line
[myTextField setBorderStyle:UITextBorderStyleLine];

// Border Style Bezel
[myTextField setBorderStyle:UITextBorderStyleBezel];

// Border Style Rounded Rect
[myTextField setBorderStyle:UITextBorderStyleRoundedRect];

The border style is not terribly exciting. However, you can really spruce up your UITextFields using the background property. Here is an example of setting the background property to this image.

myTextField.textAlignment = UITextAlignmentCenter;
myTextField.textColor = [UIColor whiteColor];
myTextField.borderStyle = UITextBorderStyleNone;
myTextField.background = [UIImage imageNamed:@"bg.png"];

and the result… Looks pretty good ehh? One GOTCHA that I want to point out here is, to get the background property to work correctly, you must set the boderStyle to anything other than UITextBorderStyleRoundedRect. Otherwise, the default UITextField will be displayed.
Setting the view’s background appearance

Managing Overlay Views

Another interesting way of customizing your UITextFields is to use an overlay. UITextField offers a left and right overlay for your UITextFields. Here are the properties:

clearButtonMode The circled X that gets displayed when typing. Used to clear out the text. Possible values: UITextFieldViewModeNever, UITextFieldViewModeWhileEditing, UITextFieldViewModeUnlessEditing, UITextFieldViewModeAlways
leftView The view that appears to the left inside a UITextField. This could be something like a magnifying glass for search.
leftViewMode Works like clearButtonMode, but toggles the leftView.
rightView Same as leftView, except it aligns to the right.
rightViewMode Same as leftViewMode but controls the rightView

Let’s take a look at how adjusting the leftView works:

UIImageView * myView = [[ UIImageView  alloc ]  initWithImage :
		[UIImage  imageNamed : @"wordpress.png" ]];
[myTextField  setLeftView :myView];
[ myTextField   setLeftViewMode: UITextFieldViewModeAlways];
[myView release ];

As you can see, the text aligns after the image. This is a very simple way to really spruce up your UITextFields.

The last thing we are going to discuss is showing and hiding the keyboard.

Showing and Hiding The Keyboard

To show the keyboard:

[myTextField becomeFirstResponder];

To hide the keyboard

[myTextField resignFirstResponder];

Well, I hope you have enjoyed this tutorial on the UITextField.  I would love to see links to some interesting custom UITextFields in the comments, so please post them.  Thanks for reading and happy iCoding!

 

UITextField – A Complete API Overview | iPhone Programming Tutorials.