2013-08-28 39 views
4

我在我的UIView的圖層屬性中畫了幾行。 但是有沒有一種方法來清理我畫的所有線?UIView的iOS清除層

我想清除在我的視圖層上繪製的所有內容。

我畫一條線用下面的代碼:

- (void)drawLine :(UIView *)drawInView :(CGPoint)startPosition :(CGPoint)endPosition 
{ 
    //draw the line 
    linePath = CGPathCreateMutable(); 
    lineShape = [CAShapeLayer layer]; 

    lineShape.lineWidth = 1.0f; 
    lineShape.lineCap = kCALineCapRound;; 
    lineShape.strokeColor = [[UIColor whiteColor] CGColor]; 

    CGPathMoveToPoint(linePath, NULL, startPosition.x, startPosition.y); 
    CGPathAddLineToPoint(linePath, NULL, endPosition.x, endPosition.y); 

    lineShape.path = linePath; 
    CGPathRelease(linePath); 
    [drawInView.layer addSublayer:lineShape]; 
} 

我發現一些代碼,刪除所有我提請子層。

-(void)clearGraph :(UIView *)viewToClear 
{ 
    for (CALayer *layer in viewToClear.layer.sublayers) { 
     [layer removeFromSuperlayer]; 
    } 
} 

但是,這會給出一個例外:

2013-08-28 21:10:18.877 ServerInfo[12861:3f03] *** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <CALayerArray: 0x1f86b3b0> was mutated while being enumerated.' 
*** First throw call stack: 
(0x336ef3e7 0x3b3ea963 0x336eeec1 0x13f7d 0x158bb 0x340082fb 0x336c4857 0x336c4503 0x336c3177 0x3363623d 0x336360c9 0x33f5a5c3 0x33ffdc45 0x15843 0x34007231 0x3b8370e1 0x3b836fa8) 
libc++abi.dylib: terminate called throwing an exception 
(lldb) 

我叫NSTread裏面我的DrawLine方法。 (doParsing方法具體)。

NSThread *myThread =[[NSThread alloc]initWithTarget:self selector:@selector(callTimer) object:nil]; 
    [myThread start]; 

- (void)callTimer 
{ 
    NSRunLoop* runLoop = [NSRunLoop currentRunLoop]; 
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(doParsing) userInfo:nil repeats:YES]; 
    [runLoop run]; 
} 

回答

8

調用CGContextClearRect與當前上下文和rect清除。


根據您更新的代碼,您實際上沒有繪製任何東西。你實際上是在添加子圖層。所以,要刪除任何以前的行,你需要刪除子層。你需要想出一個方法來找到合適的子層(也許是通過標籤來保存一個屬性),然後你可以像添加它一樣去除它。


不要執行自己的循環,獲取數組做到這一點:

[viewToClear.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)]; 
+0

嗨,Thx給你回答。我用我用來畫線的方法更新了我的問題。你能告訴我在這種情況下我的背景是什麼? –

+0

Thx爲您的答案,你打開了我的眼睛。我創建了一個清除每個圖層的for循環,但是我得到一個錯誤在枚舉時發生了變化。'這可能是因爲我在清除它後立即添加一個新行。有任何想法嗎? –

+0

如果您正在循環訪問數組,則無法對其進行更改。取一個數組的副本並迭代它。 – Wain

10

一個更簡單的方法來消除所有的子層的一個UIView是其子層屬性設置爲無

viewToClear.layer.sublayers = nil; 
4

我用了一些非常類似於Erwan的迴應..但事實證明,我不需要'圖層'部分。這是對我有用的東西。小而有效。

imageLayer.sublayers = nil;