如何使用“滑动手势”更改背景颜色

时间:2013-03-25 03:26:49

标签: objective-c uiview background-color uicolor uiswipegesturerecognizer

我有一个使用我的颜色设置的数组,但是当我滑动视图时,它总是将颜色更改为数组中的最后一项。

我错过了什么?我的for循环设置正确吗?

这是我的代码:

- (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;
    }

}

谢谢!

1 个答案:

答案 0 :(得分:1)

不,您的循环设置不正确。每次滑动都不应该循环。整个循环执行每次滑动。这将逐步浏览每种颜色,并将视图的颜色设置为该颜色。当然,最后一种颜色是可见的颜色。

相反,将索引保留在内存中,并在每次滑动时递增/递减它。每次滑动后,更新视图的颜色。

// 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;
}