如何检查CALayer是否存在
我有一个 CALayer,它在 y 轴上以动画形式(移动)到屏幕外。 当它离开屏幕后,我正在执行 [myLayer removeFromSuperLayer]
因此它从视图中消失并且不会返回到起始位置。
当图层仍在视图中时,可以通过按下切换按钮来暂停和恢复,这一切正常。
唯一的问题是,在 [myLayer removeFromSuperLayer]
运行后我的应用程序崩溃了。 这是由于按钮试图暂停或恢复不再存在的图层所致。
如何检查图层是否已删除或仍在视图中?
我认为切换按钮的暂停部分是这样的:
if (self.myLayer == nil)
{
// here i want to add the layer again
[self.view.layer addSublayer:myLayer];
// immediately pause it
[self pauseLayer:myLayer];
}
else
{
// just pause no need to create the layer again because it's still there
[self pauseLayer:myLayer];
}
正如您可能怀疑 self.myLayer == nil 不是这样做的方法,但什么是呢?
提前致谢。
I have a CALayer which animates (moves) off-screen on the y axis.
After it's off-screen i'm doing a [myLayer removeFromSuperLayer]
so its gone from the view and does not go back to start position.
While the layer is still in the view it can be paused and resumed by pushing a toggle button and this works all fine.
The only thing is that after the [myLayer removeFromSuperLayer]
has run my app crashes.
This is caused by the fact the button is trying to pause or resume the layer which doesn't exist anymore.
How can i check if the layer is removed or still in the view?
I thought something like this for the pause part of my toggle button:
if (self.myLayer == nil)
{
// here i want to add the layer again
[self.view.layer addSublayer:myLayer];
// immediately pause it
[self pauseLayer:myLayer];
}
else
{
// just pause no need to create the layer again because it's still there
[self pauseLayer:myLayer];
}
As you might suspect the self.myLayer == nil
is not the way to do it, but what is?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从其超级层中删除图层不会导致该图层变为 nil,这就是为什么您的
self.myLayer == nil
检查不起作用。但是,当您删除该字段时,您可以轻松地将其设置为 nil,例如:当然,如果您需要在此之后再次添加它,那么您需要将图层重新分配给 self.myLayer (如果您在其他地方保留了对它的引用)或从头开始创建该图层的新实例。
Removing a layer from its superlayer will not cause the layer to become nil, which is why your
self.myLayer == nil
check is not working. However, you could easily set the field to nil when you remove it, like:Of course, if you need to add it again after that then you'd need to either reassign the layer to
self.myLayer
(if you have a reference to it that you're keeping somewhere else) or create a new instance of the layer from scratch.