What is the use of removeFromSuperView in iphone?

2019-04-14 16:37发布

问题:

In my program, if i put the below line in cellForRowAtIndexPath(Tableview), the scrolling is fine. Otherwise, the lines are crashed. I want to know what this code did?

The code is....

for (UIView *oldViews in cell.contentView.subviews)
{
    [oldViews removeFromSuperview];
}

Thanks in advance

回答1:

You have to know that in iOS you are manipulating "views". Views are UI parts (images, labels, inputs etc.) or a containing layer.

At the launch beginning you MUST add a view to you window. Then you can add add as many views your want on your view.

If you add a view B on a view A. And the view A on the window.

Semantic is :

  • View A is the superview of B
  • View B is a subview of A
  • View A is a subview of the window
  • The window is the superview of view A

    So if you invoke removeFromSuperview on B, you removing B to be on A (and to be displaying).

Please note :

When you add a subview (addSubview:) a retain is performed on the view added.

When you remove a view (removeFromSuperview: or removeSubviewAtIndex:) a release is performed on the view removed.

To answer to you initial question

for (UIView *oldViews in cell.contentView.subviews)
{
    [oldViews removeFromSuperview];
}

Perform the removeFromSuperview method on every cell.contentView subviews. So old views are removed from the screen but not necessary deallocated (they are released so retainCount - 1).



回答2:

Then it's simple

Each UIView inside "cell.contentView.subviews" (so the subviews of cell.contentView), are removed.

It will remove them from the superview, and probably call the dealloc method if the retainCount is 0.



回答3:

It simply removes all subviews from cell.contentView.



回答4:

Each UIView class or sub-class can maintain his view hierarchies by addSubView:, and those codes will remove all subviews from cell.contentView.

But the instances of UITableViewCell often re-used by dequeueReusableWithIdentifier:. Those codes will remove all its subviews so if it needs to be reused, it must re-build its all sub views again.



标签: iphone uiview