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

답변

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

위대한 작품! 도와 주셔서 대단히 감사합니다! –

+0

@LukeIrvin 잘 듣고 다행했습니다! –

관련 문제