简体   繁体   中英

How do I change background color using Swipe Gesture

I have an array set up with my colors, but when I swipe the view it always changes the color to the last item in the array.

What am I missing? Is my for loop set up correctly?

Here's my code:

- (void)singleLeftSwipe:(UISwipeGestureRecognizer *)recognizer
{
    UIColor * whiteColor = [UIColor whiteColor];
    UIColor * blueColor = [UIColor blueColor];
    UIColor * redColor = [UIColor redColor];

    _colorArray = [[NSArray alloc] initWithObjects:blueColor, redColor, whiteColor, nil];

    for (int i = 0; i < [_colorArray count]; i++)
    {
        id colorObject = [_colorArray objectAtIndex:i];
        _noteView.aTextView.backgroundColor = colorObject;
    }

}

Thanks!

No, your loop is not set up correctly. You shouldn't be looping with every swipe. The entire loop executes every swipe. This steps through every color and sets the view's color to that color. Naturally, the last color is the one that gets seen.

Instead, keep an index in memory and increment / decrement it with each swipe. After each swipe, update the color of your view.

// Declare two new properties in the class extension
@interface MyClass ()

@property (nonatomic) NSInteger cursor;
@property (nonatomic, strong) NSArray *colorArray;
...

@end

//In your designated initializer (may not be init depending on your superclasses)
//Instantiate the array of colors to choose from.
- (id)init {
    self = [super init];
    if (self) {
        _colorArray = @[ [UIColor whiteColor], [UIColor blueColor], [UIColor redColor] ];
    }
    return self;
}

//Implement your gesture recognizer callback.
//This handles swipes to the left and right. Left swipes advance cursor, right swipes decrement
- (void)singleSwipe:(UISwipeGestureRecognizer *)recognizer
{
    UISwipeGestureRecognizerDirection direction = [recognizer direction];
    if (direction == UISwipeGestureRecognizerDirectionLeft) {
        // Increment cursor
        self.cursor += 1;
        // If cursor is outside bounds of array, wrap around.
        // Chose not to use % to be more explicit.
        if (self.cursor >= [self.colorArray count]) {
            self.cursor = 0;
        }
    }
    else if (direction == UISwipeGestureRecognizerDirectionRight) {
        // Decrement cursor
        self.cursor -= 1;
        // If outside bounds of array, wrap around.
        if (self.cursor < 0) {
            self.cursor = [self.colorArray count] - 1;
        }
    }

    // After adjusting the cursor, we update the color.
    [self showColorAtCursor];
}


// Implement a method to change color
- (void)showColorAtCursor
{
    UIColor *c = self.colorArray[self.cursor];
    _noteView.aTextView.backgroundColor = c;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM