Question

I am following a tutorial and I am a bit confused on this line of code...

sideView.frame = CGRectMake(gesture.direction == UISwipeGestureRecognizerDirectionRight ? -swipedCell.frame.size.width : swipedCell.frame.size.width, swipedCell.frame.origin.y, swipedCell.frame.size.width, swipedCell.frame.size.height);

What does gesture.direction == UISwipeGestureRecognizerDirectionRight ? -swipedCell.frame.size.width : mean?

I have never seen it in my experience. What does the == and ? - and : mean in this statement? Or could you explain the whole thing? What would this make the frame if I swiped left, and right?

Thanks a lot.

Was it helpful?

Solution

It's a short form if statement and could be written:

if (gesture.direction == UISwipeGestureRecognizerDirectionRight) {
    sideView.frame = CGRectMake(-swipedCell.frame.size.width, swipedCell.frame.origin.y, swipedCell.frame.size.width, swipedCell.frame.size.height);
} else {
    sideView.frame = CGRectMake(swipedCell.frame.size.width, swipedCell.frame.origin.y, swipedCell.frame.size.width, swipedCell.frame.size.height);
}

== is just the standard equivalence check. ? is the start of a short form if operator and is completed by the :.


As rmaddy pointed out, the above isn't strictly what's going on, it's more like:

CGFloat x;

if (gesture.direction == UISwipeGestureRecognizerDirectionRight) {
    x = -swipedCell.frame.size.width;
} else {
    x = swipedCell.frame.size.width;
}

sideView.frame = CGRectMake(x, swipedCell.frame.origin.y, swipedCell.frame.size.width, swipedCell.frame.size.height);

OTHER TIPS

Question mark (?) in the condition is called a ternery operator.

Before ? operator, the statement shows condition. After ? operator, first choice says the fulfilment of condition and the second shows violence of condition. So, basically it is short form of if-else.

if (gesture.direction == UISwipeGestureRecognizerDirectionRight)
{
    sideView.frame = CGRectMake(-swipedCell.frame.size.width, swipedCell.frame.origin.y, swipedCell.frame.size.width, swipedCell.frame.size.height);
}
else
{
    sideView.frame = CGRectMake(swipedCell.frame.size.width, swipedCell.frame.origin.y, swipedCell.frame.size.width, swipedCell.frame.size.height);
}

CGRectMake's signature is CGRectMake(x, y, width, height);

In this case the sideView would move to left and be hidden if you swipe in the right direction which is achieved by giving a negative x value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top