2014-02-22 31 views
0

我經常發現自己重複代碼,所以我想創建一個方法來處理它,並刪除了很多重複。我很難理解方法,所以有人可能會建議我如何創建一個自定義方法來處理touchesBegan方法中的重複代碼。寫我自己的方法 - SpriteKit

感謝

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 

for (vLineName in vLineArray) { 

    NSString *value = [vLineArray objectForKey:vLineName]; 
    SKAction *changeLineToDark = [SKAction setTexture:[SKTexture textureWithImageNamed:@"darkTexture.png"]]; 


    for (UITouch *touch in touches) { 
     CGPoint touchPoint = [touch locationInNode:self]; 
     SKSpriteNode *box = (SKSpriteNode *)[self childNodeWithName:value]; 
     if (CGRectContainsPoint(box.frame, touchPoint)) { 
      [box runAction:changeLineToDark]; 
      box.zPosition = 2; 
      NSLog (@"Just Touched %@", vLineName); 
     } 
    } 
} 

for (hLineName in hLineArray) { 

    NSString *value = [hLineArray objectForKey:hLineName]; 
    SKAction *changeLineToDark = [SKAction setTexture:[SKTexture textureWithImageNamed:@"darkTexture.png"]]; 


    for (UITouch *touch in touches) { 
     CGPoint touchPoint = [touch locationInNode:self]; 
     SKSpriteNode *box = (SKSpriteNode *)[self childNodeWithName:value]; 
     if (CGRectContainsPoint(box.frame, touchPoint)) { 
      [box runAction:changeLineToDark]; 
      box.zPosition = 2; 
      NSLog (@"Just Touched %@", hLineName); 
     } 
    } 
} 
} 

回答

0

您可以提取的touchesBegan代碼:withEvent:方法方法,如:

-(void)handleTouch:(NSSet *)touches 
{ 
    for (vLineName in vLineArray) { 

    NSString *value = [vLineArray objectForKey:vLineName]; 
    SKAction *changeLineToDark = [SKAction setTexture:[SKTexture textureWithImageNamed:@"darkTexture.png"]]; 


    for (UITouch *touch in touches) { 
     CGPoint touchPoint = [touch locationInNode:self]; 
     SKSpriteNode *box = (SKSpriteNode *)[self childNodeWithName:value]; 
     if (CGRectContainsPoint(box.frame, touchPoint)) { 
      [box runAction:changeLineToDark]; 
      box.zPosition = 2; 
      NSLog (@"Just Touched %@", vLineName); 
     } 
    } 
} 

for (hLineName in hLineArray) { 

    NSString *value = [hLineArray objectForKey:hLineName]; 
    SKAction *changeLineToDark = [SKAction setTexture:[SKTexture textureWithImageNamed:@"darkTexture.png"]]; 


    for (UITouch *touch in touches) { 
     CGPoint touchPoint = [touch locationInNode:self]; 
     SKSpriteNode *box = (SKSpriteNode *)[self childNodeWithName:value]; 
     if (CGRectContainsPoint(box.frame, touchPoint)) { 
      [box runAction:changeLineToDark]; 
      box.zPosition = 2; 
      NSLog (@"Just Touched %@", hLineName); 
     } 
    } 
} 
} 
每當屏幕被觸摸時

而且你可以把它叫做:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [self handleTouch:touches]; 
}