I create multiple objects under the same name and adding them into the Subview (variables are in german).
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
}
(Creating a row of walls)
But if I want to remove them with wand1.removeFromSuperview()
it only removes the last object it added. A possible solution I found is putting another object on top and delete all references. With many object and many stages the problem is the CPU usage.
Edit: Using the method self.view.subviews.removeAll()
is getting me following error:
Cannot use mutating member on immutable value: 'subviews' is a get-only property
wand1 = UIImageView(... is rewriting your reference over and over, so you will never be able to remove anything but the last item created from the superview. You are either going to have to use an array or dictionary:
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();
}
Or you can create object references for every image you create, each with a unique name
//NO LONGER ALLOWED
If you just want to remove all subviews from a view and not concerned about removing specifics, just call self.subviews.removeAll()
where self is the view that contains your subviews.
//
Looks like you will have to write your own extension method to handle this:
extension UIView
{
func clearSubviews()
{
for subview in self.subviews as! [UIView] {
subview.removeFromSuperview();
}
}
}
Then to use it, it is just self.view.clearSubviews();