how to remove subviews from scrollview?

后端 未结 8 2229
时光取名叫无心
时光取名叫无心 2020-12-02 09:10

how do i remove all subviews from my scrollview...

i have a uiview and a button above it in the scrollview something like this....

here is my code to add sub

8条回答
  •  情话喂你
    2020-12-02 09:13

    The best and easiest is to use

    for(UIView *subview in [scrollView subviews])
    {
      [subview removeFromSuperview];
    }
    

    This indeed causes crash as the basic rule is array shouldn't modified while being enumerated, to prevent that we can use

    [[scrollView subviews] 
               makeObjectsPerformSelector:@selector(removeFromSuperview)];
    

    But sometimes crash is still appearing because makeObjectsPerformSelector: will enumerate and performs selector, Also in iOS 7 ui operations are optimized to perform more faster than in iOS 6, Hence the best way to iterate array reversely and remove

    NSArray *vs=[scrollView subviews];
    for(int i=vs.count-1;i>=0;i--)
    {
        [((UIView*)[vs objectAtIndex:i]) removeFromSuperview];
    }
    

    Note : enumerating harms modification but not iterating...

提交回复
热议问题