2012-06-29 27 views
0

我試圖建立在如下所示的外部類中的方法:調用Draw方法外到ViewController

myClass.m

- (void)drawSomeStuffInContext:(CGContextRef)context atStartingPoint:(CGPoint *)coords 
{ 
    //draw some stuff (ignoring coords for now) 
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor); 
    CGContextSetLineWidth(context, 1.0f); 
    CGContextMoveToPoint(context, 10, 10); 
    CGContextAddLineToPoint(context, 100, 50); 
    CGContextStrokePath(context); 
} 

viewController.m

- (void)viewDidLoad 
{ 
    CGContextRef currentContext = UIGraphicsGetCurrentContext(); 
    CGPoint startCoords = CGPointMake(100.0, 100.0); 
    [[myClass alloc] drawSomeStuffInContext:currentContext atStartingPoint:startCoords]; 
} 

該項目建立並運行,但我收到日誌中沒有任何繪製的以下錯誤:

[...] <Error>: CGContextSetStrokeColorWithColor: invalid context 0x0 
[...] <Error>: CGContextSetLineWidth: invalid context 0x0 
[...] <Error>: CGContextMoveToPoint: invalid context 0x0 
[...] <Error>: CGContextAddLineToPoint: invalid context 0x0 
[...] <Error>: CGContextDrawPath: invalid context 0x0 

我一直在網上搜索類似的問題/沒有運氣的例子。是否需要不同的/附加的參數?我應該從viewDidLoad以外的其他地方調用抽獎方法嗎?建議非常感謝!

回答

1

drawRect沒有被調用(據我所知),這意味着該視圖根本沒有被繪製。你應該調用像[super initWithFrame:frame];其中frame是一個CGRect(很明顯)在drawSomeStuffInContext方法中。

您可以調用[[myClass alloc] initWithFrame:frame];在viewController.m的viewDidLoad方法中,並將起始點存儲在全局變量中。

+0

'myClass'目前被分類爲一個'NSObject',它爲我返回一些計算結果。我應該將'drawSomeStuffInContext'移動到另一個從UIView'繼承的類嗎?我似乎錯過了關於使用當前設置執行'drawRect'的事情。非常感謝您的迴應! – Jesse

+1

如果你想繪製任何東西到屏幕上,那麼類必須是它的子類的UIView。所以你可以讓這個類成爲UIView的一個子類 – prince

+0

我最終把所有的東西都移到了'drawRect'中,這個技巧已經成功了。我想我也可以從'drawRect'調用我的方法。 – Jesse

相關問題