好的,最简单的方法是设置画布以侦听 C4Shape 内部调用的正确方法(实际上,它来自任何 C4Control,因此该技术适用于所有视觉对象。
- 首先,创建一个形状并将其添加到画布上。
- 向形状添加手势,触发相应的操作
swipe
method
- 告诉画布监听
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
has有一个:
像这样:
@"randomColor:"
第三,通过从发送的通知中拉出刚刚收到滑动手势的对象来获取它:
C4Shape *shape = (C4Shape *)notification.object;