安全地删除带有标签的子视图
这不是一个真正的问题,我只是想澄清一下。 我在 UIButton 上添加一些子视图(每个按钮都有一个标签),我知道可能有 4 或 5 个子视图。 因此,当我想删除一些子视图(特别是本例中的第 4 个和第 5 个子视图)时:
int cnt=[[(UIView *)[self.scrollView viewWithTag:index] subviews] count];
if (cnt==4) {
[[[(UIView *)[self.scrollView viewWithTag:index] subviews] objectAtIndex:3] removeFromSuperview];
}
if (cnt==5) {
[[[(UIView *)[self.scrollView viewWithTag:index] subviews] objectAtIndex:3] removeFromSuperview];
//[[[(UIView *)[self.scrollView viewWithTag:index] subviews] objectAtIndex:4] removeFromSuperview]; <-- this crash
[[[(UIView *)[self.scrollView viewWithTag:index] subviews] objectAtIndex:3] removeFromSuperview];
}
当然,注释行无法执行,因为没有更多的 5 个子视图,而是 4 个子视图。 所以我必须删除两次指向同一索引的视图。 我想知道这是否是删除它们的安全方法,并且我想确保最后一个视图在数组中移动到较低的位置 [[self.scrollView viewWithTag:index] subviews]
。
希望它是清楚的。 谢谢
This is not a real problem, i want just a clarification.
I'm adding some subviews on a UIButton(each button has a tag), i know that there may be either 4 or 5 subviews.
So, when i want to remove some subviews(specifically the 4th and 5th in this case):
int cnt=[[(UIView *)[self.scrollView viewWithTag:index] subviews] count];
if (cnt==4) {
[[[(UIView *)[self.scrollView viewWithTag:index] subviews] objectAtIndex:3] removeFromSuperview];
}
if (cnt==5) {
[[[(UIView *)[self.scrollView viewWithTag:index] subviews] objectAtIndex:3] removeFromSuperview];
//[[[(UIView *)[self.scrollView viewWithTag:index] subviews] objectAtIndex:4] removeFromSuperview]; <-- this crash
[[[(UIView *)[self.scrollView viewWithTag:index] subviews] objectAtIndex:3] removeFromSuperview];
}
The commented line can not be executed, of course, because there aren't more 5, but 4 subviews.
So I have to remove the view pointing twice on the same index.
I would like to know if it's a safe way to remove them, and i want to be sure that the last view is moved one position lower in the array [[self.scrollView viewWithTag:index] subviews]
.
Hope it is clear.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您知道要删除的视图的标签,那么更安全的方法是:
在这里,您要求子视图删除自身,而不是要求父视图根据某些可能的假设顺序删除子视图。错了。
If you know the tags of the views that you want to remove then a safer way of doing this is:
Here you are asking the child view to remove itself, rather than asking the parent view to remove the child based on some assumed ordering that may be wrong.
我宁愿使用这样的东西:
通常,当从列表中删除对象时,最安全的方法是从末尾开始。这样一来,即使重组也没关系。
I'd rather use something like this:
Usually, when removing objects from lists, the safest method is to begin at the end. This way it doesn't even matter if they get reorganized.