我添加了一個梯度層卸下的CALayer:在索引0
[theView.layer insertSublayer:gradient atIndex:0];
和稍後在另一種方法中我想刪除這一層。我想我應該得到的數組子層,然後得到索引0的子層,並調用removeFromSuperlayer。這是正確的方式,否則你能做到嗎?
乾杯。
我添加了一個梯度層卸下的CALayer:在索引0
[theView.layer insertSublayer:gradient atIndex:0];
和稍後在另一種方法中我想刪除這一層。我想我應該得到的數組子層,然後得到索引0的子層,並調用removeFromSuperlayer。這是正確的方式,否則你能做到嗎?
乾杯。
您可以按照您所描述的方式進行操作,但它不太可靠。問題是,如果您在添加和刪除之間對子層進行了任何操作,子層的索引可能會發生變化,最終會刪除您不想要的內容。
的最好的事情是,當你想刪除它只是調用[theLayer removeFromSuperlayer]
希望它可以幫助
Funfunfun保持到該層的引用,後來...
有兩個圖層屬性你可以使用(無論哪種情況下,你必須遍歷圖層):
CALayer.name
「被某些佈局管理器用來識別層R」。將其設置爲合理確保唯一的內容(例如「MyClassName.gradient」)。CALayer.style
是一本字典。您可以使用CoreAnimation未使用的鍵(例如NSMutableDictionary * d = [NSMutableDictionary dictionaryWithDictionary:layer.style]; [d setValue:[NSNumber numberWithBool:YES] forKey:@"MyClassName.gradient"]; layer.style = d;
)。這可能會將任意數據與視圖相關聯(例如包含文本字段的單元格的索引路徑...)。(我假設[NSDictionary dictionaryWithDictionary:nil]
返回空字典,而不是返回零或拋出異常的,相應的一點是[NSArray arrayWithArray:nil]
真的。)
但是,額外的代碼的複雜性,性能損失,並且出錯的機率可能超過內存使用量的小幅下降。如果您有少量視圖(即使您有負載,4個字節是單個像素使用的內存!),每個視圖4個字節也不會太多。
有趣的是,CALayer的名字可能很有用,因爲我可以很容易地唯一標識它,但正如你所說的,由於循環遍歷視圖中的所有圖層來找到一個額外的編碼和性能,基於名字與稍微額外的內存可能不值得。這和我已經實現了另一種方式。 – Rudiger 2010-11-23 05:42:00
舊帖子..但是這可能是有人有幫助...
我執行刪除/更換的CALayer。使用Calayer.name作爲tc。如上所述。
CAGradientLayer *btnGradient = [CAGradientLayer layer];
btnGradient.frame = button.bounds;
btnGradient.name = @"gradient";
btnGradient.colors = nil;
btnGradient.colors = [NSArray arrayWithObjects:
(id)[[VOHelper getButtonColor:kSchemeBorder] CGColor],
(id)[[VOHelper getButtonColor:kSchemeButton] CGColor],
nil];
if ([[[[button.layer sublayers] objectAtIndex:0] name] isEqualToString:@"gradient"]){
[button.layer replaceSublayer:[[button.layer sublayers] objectAtIndex:0] with:btnGradient];
}
else{
[button.layer insertSublayer:btnGradient atIndex:0];
}
斯威夫特有一些這方面的真正簡單的解決方案:
if self.yourView.layer.sublayers!.count > 1 {
// Will remove the last sublayer
self.yourView.layer.sublayers!.popLast()
// Will remove the layer at specified index
self.yourView.layer.sublayers!.removeAtIndex(1)
}
只記得,子層被視爲一個數組,所以如果你有計數2,然後2 == 1中指數,因此removeAtIndex(1)
。
有可用於編輯子層選項的一大堆。只需在sublayers!.
之後停止輸入,並將其簽出。
我很害怕這個:( – Rudiger 2010-11-22 22:30:01