Saturday, June 8, 2013

UITableViewCell setSelectedBackgroundView example in Objective C (iOS).


UITableViewCell setSelectedBackgroundView

The view used as the background of the cell when it is selected.

@property(nonatomic, retain) UIView *selectedBackgroundView

Discussion of [UITableViewCell setSelectedBackgroundView]
The default is nil for cells in plain-style tables (UITableViewStylePlain) and non-nil for section-group tables UITableViewStyleGrouped). UITableViewCell adds the value of this property as a subview only when the cell is selected. It adds the selected background view as a subview directly above the background view (backgroundView) if it is not nil, or behind all other views. Calling setSelected:animated: causes the selected background view to animate in and out with an alpha fade.

UITableViewCell setSelectedBackgroundView example.
UIView * selectedBackgroundView = [[UIView alloc] initWithFrame:self.frame];
[selectedBackgroundView setBackgroundColor:[UIColor redColor]]; // set color here
[self setSelectedBackgroundView:selectedBackgroundView];
[selectedBackgroundView release];
or you can configure it in -tableView:cellForRowAtIndexPath: method:

//...
[cell setSelectedBackgroundView:selectedBackgroundView];
//...

Example of [UITableViewCell setSelectedBackgroundView].
UIImageView *imv = [[UIImageView alloc]init];
imv.backgroundColor=[UIColor redColor];
[cell setSelectedBackgroundView:imv];
CALayer *layer = imv.layer;
[layer setMasksToBounds:YES];
[layer setCornerRadius:10.0];
[imv release];

UITableViewCell setSelectedBackgroundView example.
UIView *selctionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)] autorelease];

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = selctionView.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blueColor] CGColor], (id)[[UIColor redColor] CGColor], nil];

[selctionView.layer insertSublayer:gradient atIndex:0];

[self setSelectedBackgroundView:selctionView];

End of UITableViewCell setSelectedBackgroundView example article.