Swift:从子视图中删除所有内容

时间:2015-10-22 13:46:17

标签: swift uiimageview subview superview

我使用相同的名称创建多个对象并将它们添加到子视图中(变量是德语)。

    wandX = (screenBreite - ((felderAnzX - 0) * feldBreite))
    wandY = ( screenHoehe - ((felderAnzY - 5) * feldBreite))

    for(var i = 0; i < 6; i++){
        wand1 = UIImageView(frame: CGRectMake(wandX, wandY, feldBreite, feldBreite))
        wand1.image = wand
        self.addSubview(wand1)
        wandXarray.insert(wandX, atIndex: i)
        wandYarray.insert(wandY, atIndex: i)
        wandX = wandX + feldBreite
    }

(创建一排墙)

但是如果我想用wand1.removeFromSuperview()删除它们,它只删除它添加的最后一个对象。我找到的一个可能的解决方案是将另一个对象置于顶部并删除所有引用。对于许多对象和许多阶段,问题是CPU使用率。

编辑:使用方法self.view.subviews.removeAll()让我遇到以下错误:

  

不能在不可变值上使用变异成员:&#39; subviews&#39;是一个只获得属性

1 个答案:

答案 0 :(得分:2)

wand1 = UIImageView(...一遍又一遍地重写你的引用,所以除了从superview创建的最后一项之外你永远无法删除任何东西。你要么必须使用数组或字典:< / p>

class Class
{
    var array = [UIImageView]();
    ...
    func something()
    {
    ...
    for(var i = 0; i < 6; i++){
    let wand1 = UIImageView();
    wand1.image = wand
    array.append(UIImageView(frame: CGRectMake(wandX, wandY, feldBreite, feldBreite)))
    self.add.Subview(wand1)//Dunno how this works but it is your code
    wandXarray.insert(wandX, atIndex: i)
    wandYarray.insert(wandY, atIndex: i)
    wandX = wandX + feldBreite
   }
   ...
   func removeThisImage(index : Int)
   {
       array[index].removeFromSuperView();
   }

或者您可以为您创建的每个图像创建对象引用,每个图像都具有唯一的名称

//不允许更长时间 如果您只想从视图中删除所有子视图而不关心删除细节,只需调用self.subviews.removeAll()其中self是包含您的子视图的视图。 //

看起来你必须编写自己的扩展方法来处理这个问题:

extension UIView
{
    func clearSubviews()
    {
        for subview in self.subviews as! [UIView] {
            subview.removeFromSuperview();
        }
    }
}

然后使用它,它只是self.view.clearSubviews();

相关问题