Reputation: 931
I want to change a view backgroundColor
while it is receiving UILongPressGesture
, how can I do it properly? With the code below everything freezes forever, even if I lift my finger it won't unfreeze.
- (void)longPress:(UILongPressGestureRecognizer *)gesture {
while ([gestureRecognizer state] == UIGestureRecognizerStateChanged) {
[self.Row2View setBackgroundColor:[UIColor colorWithWhite:0.5 alpha:0.2]];
}
}
EDIT What I need is: While UILongPressGesture
change color , When finger lifts the screen change color back.
Upvotes: 0
Views: 60
Reputation: 2337
Add a property
@property (copy) UIColor *initialBackgroundColor;
Handle Long Press
- (void)longPress:(UILongPressGestureRecognizer *)gesture
{
if ([gesture state] == UIGestureRecognizerStateBegan)
{
self.initialBackgroundColor = self.Row2View.backgroundColor;
[self.Row2View setBackgroundColor:[UIColor colorWithWhite:0.5 alpha:0.2]];
}
else if ([gesture state] == UIGestureRecognizerStateEnded ||
[gesture state] == UIGestureRecognizerStateCancelled ||
[gesture state] == UIGestureRecognizerStateFailed)
{
[self.Row2View setBackgroundColor:self.initialBackgroundColor];
}
}
Upvotes: 0
Reputation: 1722
you use while! when enter the loop, the condition will always be true!
first,change while to if. then according to apple document:
Long-press gestures are continuous. The gesture begins (
UIGestureRecognizerStateBegan
) when the number of allowable fingers (numberOfTouchesRequired
) have been pressed for the specified period (minimumPressDuration
) and the touches do not move beyond the allowable range of movement (allowableMovement
). The gesture recognizer transitions to the Change state whenever a finger moves, and it ends (UIGestureRecognizerStateEnded
) when any of the fingers are lifted.
I think you should use Began State(when gesture got recognized) or Ended State(when a recognized gesture release up). if you don't want to call method continuously when touch moves.
if ([gesture state] == UIGestureRecognizerStateBegan) {
[self.Row2View setBackgroundColor:[UIColor colorWithWhite:0.5 alpha:0.2]];
}
--- EDIT ---
according to you description, you want to change color when touch and restore when release. so it will be:
if ([gesture state] == UIGestureRecognizerStateBegan) {
Row2ViewOriginColor = self.Row2View.backgroundColor; // you can declare this var in the class.
[self.Row2View setBackgroundColor:[UIColor colorWithWhite:0.5 alpha:0.2]];
}
else if ([gesture state] == UIGestureRecognizerStateEnded ||
[gesture state] == UIGestureRecognizerStateCancelled) {
[self.Row2View setBackgroundColor: Row2ViewOriginColor];
}
Upvotes: 1
Reputation: 1155
Because the "while" block will never break! Just change the "while" block to "if"!
Upvotes: 2