我经常发现自己重复代码,所以我想创建一个方法来处理它并减少了很多重复。我很难理解方法,所以有人可以建议我如何创建一个自定义方法来处理touchesBegan方法中重复的代码。
由于
- (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 :(得分: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];
}