我希望实现的是使用以下方法在C4Workspace.m中调用方法:
[shape addGesture:SWIPELEFT name:@"swipeLeft" action:@"leftSwipeMethod"];
我知道这会尝试在C4Shape类中调用一个名为“leftSwipeMethod”的方法,但是在文档中它还提到你可以调用超类中的方法(我认为我正在尝试做什么?)
我检查过这样的其他问题,我知道你不应该在正常的目标c中做到这一点......但是我想知道C4的情况是否也是如此。
有没有其他方法可以获得相同的结果,还是我必须创建一个子类?
答案 0 :(得分:2)
好的,最简单的方法是设置画布以侦听在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;