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

} 

谢谢!

+0

你的代码应该做什么? – Sebastian 2013-03-25 03:33:57

回答

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; 
} 
+0

这工程太棒了!非常感谢你的帮助! – 2013-03-25 03:52:12

+0

@LukeIrvin很高兴听到它的工作! – 2013-03-25 22:32:36