Friday, August 14, 2009

Background Image To iPhone Grouped Table View


Want to add a nice image as background to your grouped table view.
you must have tried adding it to the tableviewcontroller using:

Wrong way

tableviewcontroller .view.backgroundColor = [UIColor colorWithPatternImage:[UIImage
imageNamed:@"backgroundimage.png"]]

Adding a background image directly to table view creates ugly artifacts on the left and right side of sections in tableview as shown in the image below:



Right Way

To display it in a right way you need to create a background image view and add that view to your window before adding the tableviewController in app delegate. then in viewDidLoad method of the tableviewController set the table view’s background color to “clearColor."

In App Delegate

UIView *backgroundView = [[UIView alloc] initWithFrame:window.frame];

backgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backgroundimage.png"]];

[window addSubview:backgroundView];

[backgroundView release];



In tableViewController

(void)viewDidLoad {

self.view.backgroundColor = [UIColor clearColor];

[super viewDidLoad];

}

Its will produce a nice background image for your table view as displayed below:






To see how it works it Xcode follow these steps:
  • create a new project.
  • select navigation based application. uncheck core data storage.
  • save project as NavigationBasedApp.
  • it will create RootViewController which has UITableViewController as its superclass.
  • open RootViewController.xib file in interface builder.
  • Open inspector and go to tableview attributes.
  • change style of the table to grouped and save your file.
  • come back to Xcode and open NavigationBasedAppAppDelegate.m
  • in applicationDidFinishLaunching method made the following changes

- (void)applicationDidFinishLaunching:(UIApplication *)application {

// Override point for customization after app launch

UIView *backgroundView = [[UIView alloc] initWithFrame:window.frame];

backgroundView.backgroundColor = [UIColor colorWithPatternImage:

[UIImage imageNamed:@"yourbackgroundImage.png"]];

[window addSubview:backgroundView];

[backgroundView release];

[window addSubview:[navigationController view]];

[window makeKeyAndVisible];

}


  • now go to RootViewController.m and made following changes in viewDidLoad method

- (void)viewDidLoad {

self.view.backgroundColor = [UIColor clearColor];

[super viewDidLoad];

}


  • thats it. you are ready to build and go.
  • your nice background image will be there without any artifacts

No comments: