11

I am trying to remove all the subviews from a UIView. I tried the following to no effect:

        for (int i = 0; i < this.Subviews.Length; i++)
        {
            this.Subviews[i].RemoveFromSuperview ();

        }
Ian Vink
  • 66,960
  • 104
  • 341
  • 555

4 Answers4

15

Just tested this and it worked for me. (Although your code also looks good to me...)

foreach (UIView view in tableView.Subviews) {
  view.RemoveFromSuperview();
}

If it doesn't work for you, there might be something that prevents the subviews from being removed.

riha
  • 2,270
  • 1
  • 23
  • 40
4

The problem with your sample is how you built the loop.

When you remove the view at 0, the Subviews array is one element shorter, and element 1 becomes element 0 on the next iteration. Your i variable on the other hand keeps growing, so you end up skipping view 1.

miguel.de.icaza
  • 32,654
  • 6
  • 58
  • 76
  • 1
    Something 0-based could work around that, right? Like `while (this.Subviews.Length > 0) { this.Subviews[0].RemoveFromSuperview(); }` – riha Feb 09 '11 at 11:15
0

Try forcing a refresh of the view afterward, or invoking the Remove call specifically on the main thread.

jbehren
  • 780
  • 6
  • 11
0

If you absolutely need to use an for loop, this will do

    for (int i = this.Subviews.Length - 1 ; i > 0  i--)
    {
        this.Subviews[i].RemoveFromSuperview ();
    }
Odd Morten
  • 21
  • 2