iOS - 如何删除以前添加的 UIView 子层
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37581951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS - How To Remove Previously Added Sublayers Of a UIView
提问by JLT
I have a custom view which is a subclass of UIView
. I added some sublayers to the custom view but now I want remove them.
我有一个自定义视图,它是UIView
. 我在自定义视图中添加了一些子图层,但现在我想删除它们。
I tried doing this:
我尝试这样做:
self.layer.sublayers = nil;
But this will remove everything including the initial sublayers of the view.
但这将删除所有内容,包括视图的初始子层。
Is there any way to achieve this? Or do I have to reinitialise a new custom view every time?
有没有办法实现这一目标?还是我每次都必须重新初始化一个新的自定义视图?
Note: App runs in iOS 7 and above.
注意:应用程序在 iOS 7 及更高版本中运行。
Thanks!
谢谢!
回答by luckystars
Keep a reference to the sublayer added Remove the sublayer from the super layer when not needed.
保留对添加的子层的引用 在不需要时从超级层中移除子层。
The code would be like:
代码如下:
Obj C:
对象 C:
[thesublayer removeFromSuperlayer]
Swift:
迅速:
thesublayer.removeFromSuperlayer()
//thesublayer is the name of the layer you want to remove
回答by Kiran Jasvanee
Another way to remove specific layer from super layer is to assign unique string in layer.name
property. Which you can compare later to identify and remove it out.
从超级层中删除特定层的另一种方法是在layer.name
属性中分配唯一的字符串。您可以稍后进行比较以识别并删除它。
for layer in sublayers {
if layer.name == "masklayer" {
layer.removeFromSuperlayer()
}
}
回答by meow2x
回答by mohsen
first of all you should add a name to the sublayer with theLayer.name
property
首先,您应该为具有theLayer.name
属性的子图层添加一个名称
after that you can extend the view like this:
之后,您可以像这样扩展视图:
extension UIView {
func removeLayer(layerName: String) {
for item in self.layer.sublayers ?? [] where item.name == layerName {
item.removeFromSuperlayer()
}
}
}
回答by Vanya
keeping reference is not cool, in some cases you can use
保持引用并不酷,在某些情况下你可以使用
_ = resultImageView.layer.sublayers?.filter{ - (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
// Remove player layer when screen gone
NSUInteger layerIndex = [self.view.layer.sublayers indexOfObjectPassingTest:^BOOL(__kindof CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
return [obj isKindOfClass:[AVPlayerLayer class]];
}];
if (layerIndex != NSNotFound) {
AVPlayerLayer *playerLayer = self.view.layer.sublayers[layerIndex];
[playerLayer removeFromSuperlayer];
}
}
is CAShapeLayer }.map{ ##代码##.removeFromSuperlayer() }
or to be more generic by using CALayer, which removes everything
或者通过使用 CALayer 更通用,它删除了所有内容
回答by Idan Moshe
Here is my solution for removing AVPlayerLayer
without keeping a reference to it:
这是我在AVPlayerLayer
不保留引用的情况下删除的解决方案: