好的,最简单的方法是设置您的画布以侦听在 C4Shape 内部调用的正确方法(实际上,它来自任何 C4Control,因此该技术适用于所有视觉对象。
- 首先,创建一个形状并将其添加到画布中。
- 向形状添加手势,触发相应的
swipe
方法
- 告诉画布
notification
从形状中侦听
- 当画布听到通知时做一些事情(即改变形状的颜色)
以下代码设置形状:
@implementation C4WorkSpace {
C4Shape *s;
}
-(void)setup {
s = [C4Shape rect:CGRectMake(0, 0, 192, 96)];
s.center = self.canvas.center;
[s addGesture:SWIPELEFT name:@"leftSwipeGesture" action:@"swipedLeft"];
[self.canvas addShape:s];
[self listenFor:@"swipedLeft" fromObject:s andRunMethod:@"randomColor"];
}
-(void)randomColor {
s.fillColor = [UIColor colorWithRed:[C4Math randomInt:100]/100.0f
green:[C4Math randomInt:100]/100.0f
blue:[C4Math randomInt:100]/100.0f
alpha:1.0f];
}
@end
但是,这是硬编码的……一种更好、更动态的方法是从大量对象中侦听并使用randomColor:
一种也接受通知的方法,以便您可以拉出正在执行通知的形状。
@implementation C4WorkSpace {
C4Shape *s1, *s2;
}
-(void)setup {
s1 = [C4Shape rect:CGRectMake(0, 0, 192, 96)];
[s1 addGesture:SWIPELEFT name:@"leftSwipeGesture" action:@"swipedLeft"];
s2 = [C4Shape rect:CGRectMake(0, 0, 192, 96)];
[s2 addGesture:SWIPELEFT name:@"left" action:@"swipedLeft"];
s1.center = CGPointMake(self.canvas.center.x, self.canvas.center.y - s1.height * 1.25);
s2.center = CGPointMake(self.canvas.center.x, self.canvas.center.y + s2.height * 0.25);
NSArray *shapes = @[s1,s2];
[self.canvas addObjects:shapes];
[self listenFor:@"swipedLeft" fromObjects:shapes andRunMethod:@"randomColor:"];
}
-(void)randomColor:(NSNotification *)notification {
C4Shape *shape = (C4Shape *)notification.object;
shape.fillColor = [UIColor colorWithRed:[C4Math randomInt:100]/100.0f
green:[C4Math randomInt:100]/100.0f
blue:[C4Math randomInt:100]/100.0f
alpha:1.0f];
}
@end
第二个例子需要注意的地方:
首先,要接受通知,正在运行的方法必须具有以下格式:
-(void)randomColor:(NSNotification *)notification {}
其次,要触发此操作,您使用的方法名称listenFor
必须是:
这样的:
@"randomColor:"
第三,通过从它发送的通知中拉取刚刚收到滑动手势的对象:
C4Shape *shape = (C4Shape *)notification.object;