Saturday, June 8, 2013

UITableViewCell selectedBackgroundView example in Objective C (iOS).


UITableViewCell selectedBackgroundView

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

@property(nonatomic, retain) UIView *selectedBackgroundView

Discussion of [UITableViewCell selectedBackgroundView]
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 selectedBackgroundView example.
    self.backgroundColor = [UIColor blackColor]; // Gives black background for you

    // Set selected background view
    UIView *backgroundView = [[UIView alloc]initWithFrame:self.bounds];
    backgroundView.layer.borderColor = [[UIColor colorWithRed:0.529 green:0.808 blue:0.922 alpha:1]CGColor];
    backgroundView.layer.borderWidth = 10.0f;
    self.selectedBackgroundView = backgroundView;
    [backgroundView release];

    // Set the content view
    CGRect frame  = CGRectMake(self.bounds.origin.x+5, self.bounds.origin.y+5, self.bounds.size.width-10, self.bounds.size.height-10);
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
    self.imageView = imageView;
    [imageView release];
    self.imageView.contentMode = UIViewContentModeScaleAspectFill ;
    self.imageView.clipsToBounds = YES;
    [self.contentView addSubview:self.imageView];

Example of [UITableViewCell selectedBackgroundView].
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SelectedCellBackground.png"]] autorelease];
    }

    // configure the cell
}

UITableViewCell selectedBackgroundView example.
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]))
    {
        self.clipsToBounds = YES;

        UIView* bgView = [[UIView alloc] init];
        bgView.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.25f];
        self.selectedBackgroundView = bgView;
                //other code

    }
    return self;
}

End of UITableViewCell selectedBackgroundView example article.