Saturday, June 8, 2013

UITableViewCell setHighlighted example in Objective C (iOS).


UITableViewCell setHighlighted

A Boolean value that indicates whether the cell is highlighted.

@property(nonatomic, getter=isHighlighted) BOOL highlighted

Discussion of [UITableViewCell setHighlighted]
The highlighting affects the appearance of labels, image, and background. When the highlighted state of a cell is set to YES, labels are drawn in their highlighted text color (default is white). The default value is NO. If you set the highlighted state to YES through this property, the transition to the new state appearance is not animated. For animated highlighted-state transitions, see the setHighlighted:animated: method.

Note that for highlighting to work properly, you must fetch the cell’s labels using the textLabel and detailTextLabel properties and set each label’s highlightedTextColor property; for images, get the cell’s image using the imageView property and set the UIImageView object’s highlightedImage property.

UITableViewCell setHighlighted example.
     if (indexPath.row == 0) {
    cell = [[UITableViewCell alloc ] initWithStyle:UITableViewCellStyleDefault
                                   reuseIdentifier:@"currentLoc"];
    cell.accessoryType = UITableViewCellAccessoryNone;
      cell.textLabel.text = @"This is the special cell";
    }
    [cell setHighlighted:YES animated:YES];
    [cell setHighlighted:NO animated:YES];


Example of [UITableViewCell setHighlighted].
You must also override setHighlighted: to prevent the blue gradient from ever showing. If you just override setHighlighted: then you end up with a momentary selection effect.

so you'll have these two methods:

- (void)setHighlighted: (BOOL)highlighted animated: (BOOL)animated
{
    // don't highlight
}

- (void)setSelected: (BOOL)selected animated: (BOOL)animated
{
    // don't select
    //[super setSelected:selected animated:animated];
}

UITableViewCell setHighlighted example.
save the indexpath of the selected cell

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.selectedIndexPath = indexPath;
}
and compare in tableVIew:cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    // configure cell
    if ([indexPath isEqual:self.selectedIndexPath]) {
        [cell setHighlighted:YES];
    }
    else {
        [cell setHighlighted:NO];
    }
    return cell;

}

End of UITableViewCell setHighlighted example article.