Saturday, June 8, 2013

UITableViewCell willTransitionToState example in Objective C (iOS).


UITableViewCell willTransitionToState

Called on the cell just before it transitions between cell states.

- (void)willTransitionToState:(UITableViewCellStateMask)state

Parameters of [UITableViewCell willTransitionToState]
state
A bit mask indicating the state or combination of states the cell is transitioning to.

Discussion of [UITableViewCell willTransitionToState]
Subclasses of UITableViewCell can implement this method to animate additional changes to a cell when it is changing state. UITableViewCell calls this method whenever a cell transitions between states, such as from a normal state (the default) to editing mode. The custom cell can set up and position any new views that appear with the new state. The cell then receives a layoutSubviews message (UIView) in which it can position these new views in their final locations for the new state. Subclasses must always call super when overriding this method.

Note that when the user swipes a cell to delete it, the cell transitions to the state identified by the UITableViewCellStateShowingDeleteConfirmationMask constant but the UITableViewCellStateShowingEditControlMask is not set.

UITableViewCell willTransitionToState example.
- (void)willTransitionToState:(UITableViewCellStateMask)state
{
    NSString *logStr = @"Invoked";
    if ((state & UITableViewCellStateShowingEditControlMask)
        != 0) {
        // you need to move the controls in left
        logStr = [NSString stringWithFormat:@"%@
                  %@",logStr,@"UITableViewCellStateShowingEditControlMask"];
    }
    if ((state & UITableViewCellStateShowingDeleteConfirmationMask)
        != 0) {
        // you need to hide the controls for the delete button
        logStr = [NSString stringWithFormat:@"%@
                  %@",logStr,@"UITableViewCellStateShowingDeleteConfirmationMask"];
    }
    NSLog(@"%@",logStr);
    [super willTransitionToState:state];
}

Example of [UITableViewCell willTransitionToState].
- (void)willTransitionToState:(UITableViewCellStateMask)state {

    [super willTransitionToState:state];

    if ((state & UITableViewCellStateShowingDeleteConfirmationMask) == UITableViewCellStateShowingDeleteConfirmationMask) {

        for (UIView *subview in self.subviews) {

            if ([NSStringFromClass([subview class]) isEqualToString:@"UITableViewCellDeleteConfirmationControl"]) {            

                subview.hidden = YES;
                subview.alpha = 0.0;
            }
        }
    }
}

UITableViewCell willTransitionToState example.
- (void)willTransitionToState:(UITableViewCellStateMask)state
{
    if (state == UITableViewCellStateShowingDeleteConfirmationMask) {
        swipedToDelete = YES; // BOOL ivar
    }
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    if (swipedToDelete) {
        // do your stuff, or don't
    }
}

End of UITableViewCell willTransitionToState example article.