2013-05-04 84 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