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