0

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

我错过了什么?我的 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;
    }

}

谢谢!

4

1 回答 1

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;
}
于 2013-03-25T03:34:23.877 回答