2013-05-04 35 views
1

我已经问过关于这个项目的另一个问题,而特拉维斯是超级有用的。 Previous questionC4Shape自定义子类初始化问题?

考虑到这个建议,我正在尝试为C4Shape类创建一个子类,我为这个类添加了2个属性(两个浮点数)用于X和Y位置值。我不只是调用C4Shape的.center属性的原因是因为要将它们添加到画布中,我倾向于使用左上角而不是中心。

我想为这个新类写一个自定义的Init方法,但是我得到一个错误。

这是自定义初始化代码我的工作:

customShape.m

- (id)initWithColor:(UIColor *)fillColor atX:(float)_xValue atY:(float)_yValue 
{ 
CGRect frame = CGRectMake(_xValue, _yValue, 100, 100); 
self = [customShape rect:frame]; 

self.lineWidth = 0.0f; 
self.fillColor = fillColor; 
self.xValue = _xValue; 
self.yValue = _yValue; 


return self; 
} 

C4WorkSpace.m

-(void)setup { 
customShape *testShape = [[customShape alloc]initWithColor:[UIColor greenColor] atX:50.0f atY:50.0f]; 

[self.canvas addShape:testShape]; 
} 

我怀疑罪魁祸首是self = [customShape rect:frame];这是警告我看到:“不兼容的指针类型从'C4Shape *'分配给'customeShape * _strong'”

,当我尝试运行此获取引发实际的错误是:“终止应用程序由于未捕获的异常‘NSInvalidArgumentException’,原因是:‘ - [C4Shape setXValue:]:无法识别的选择发送到实例0x9812580’”

由于在我制作可以保存颜色值的按钮之前,当您点击该按钮时,它会发送一个带有fillColor按钮以及iPad IP的UDP数据包。

回答

2

你非常接近init方法的实现。我会重新调整它以下列方式:

- (id)initWithColor:(UIColor *)aColor origin:(CGPoint)aPoint { 
    self = [super init]; 
    if(self != nil) { 
     CGRect frame = CGRectMake(0,0, 100, 100); 
     [self rect:frame]; 
     self.lineWidth = 0.0f; 
     self.fillColor = aColor; 
     self.origin = aPoint; 
    } 
    return self; 
} 

几件事情要注意:

  1. 当继承它总是好的,调用该对象的父类的init方法
  2. 这是很好的做法来包装if语句中的子类的init,检查超级类init是否正确返回。
  3. 为您的新对象创建一个框架,并直接拨打self并致电rect:
  4. 有一个在每一个可见的C4对象的origin点,这样的而不是直接使用xy值,你可以设置一个CGPoint原点(该origin是左上角)。

然后,您需要把这个方法添加到您的.h文件:

@interface MyShape : C4Shape 
-(id)initWithColor:(UIColor *)aColor origin:(CGPoint)aPoint; 
@end 

最后,你可以在你C4WorkSpace创建你的形状是这样的:

MyShape *m = [[MyShape alloc] initWithColor:[UIColor darkGrayColor] 
            origin:CGPointMake(100, 100)]; 

而且,如果你加入一个线,你可以检查按钮的原点:

-(void)heardTap:(NSNotification *)aNotification { 
    MyShape *notificationShape = (MyShape *)[aNotification object]; 
    C4Log(@"%4.2f,%4.2f",notificationShape.center.x,notificationShape.center.y); 
    C4Log(@"%4.2f,%4.2f",notificationShape.origin.x,notificationShape.origin.y); 
    C4Log(@"%@",notificationShape.strokeColor); 
} 

虽然你可以用xy值作为工作性质,我建议您用CGPoint结构的工作。这几乎是一样的,除非你从C4进入Objective-C,你会注意到CGPoint和其他CG几何结构被使用到无处不在

+0

非常感谢你特拉维斯! – BardiaD 2013-05-06 04:24:30

+0

没问题!保持提问。 – 2013-05-06 15:32:01