jak usunąć podglądy z widoku przewijania?

Jak usunąć wszystkie podglądy z widoku przewijania...

Mam uiview i przycisk nad nim w widoku przewijania coś takiego....

Oto Mój kod do dodania subview w widoku przewijania

-(void)AddOneButton:(NSInteger)myButtonTag {
lastButtonNumber = lastButtonNumber + 1;

if ((lastButtonNumber == 1) || ((lastButtonNumber%2) == 1)) {
btnLeft = 8;}
else if ((lastButtonNumber == 2) || ((lastButtonNumber%2) == 0)) {
btnLeft = 162;
}
CGRect frame1 = CGRectMake(btnLeft, btnTop, 150, 150);
CGRect frame2 = CGRectMake(btnLeft, btnTop, 150, 150);
UIButton *Button = [UIButton buttonWithType:UIButtonTypeCustom];
Button.frame = frame1;
Button.tag = myButtonTag;
[Button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[Button setBackgroundColor:[UIColor clearColor]];
[Button setBackgroundImage:[UIImage imageNamed:@"WaitScreen.png"] forState:UIControlStateHighlighted];

    GraphThumbViewControllerobj = [[GraphThumbViewController alloc] initWithPageNumber:[[GraphIdArray objectAtIndex:myButtonTag]intValue]];
    GraphThumbViewControllerobj.view.frame=frame2;
    GraphThumbViewControllerobj.lblCounter.text=[NSString stringWithFormat:@"%d of %d",myButtonTag+1,flashCardsId.count];
    GraphThumbViewControllerobj.lblQuestion.text=[flashCardText objectAtIndex:myButtonTag];
    [myScrollView addSubview:GraphThumbViewControllerobj.view];


[myScrollView addSubview:Button];


if ((lastButtonNumber == 2) || ((lastButtonNumber%2) == 0)) {
btnTop = btnTop + 162;
}
if (btnTop+150 > myScrollView.frame.size.height) {
myScrollView.contentSize = CGSizeMake((myScrollView.frame.size.width), (btnTop+160));}
}

A oto kod do usunięcia podwidywań

if(myScrollView!=nil)
{
        while ([myScrollView.subviews count] > 0) {
            //NSLog(@"subviews Count=%d",[[myScrollView subviews]count]);
            [[[myScrollView subviews] objectAtIndex:0] removeFromSuperview];
}

Alt text http://www.freeimagehosting.net/uploads/e5339a1f51.png

Author: teabot, 2009-08-21

8 answers

Aby usunąć wszystkie podviews z dowolnego widoku, możesz iterować nad podviews i wysłać każdy removeFromSuperview wywołanie:

// With some valid UIView *view:
for(UIView *subview in [view subviews]) {
    [subview removeFromSuperview];
}

Jest to jednak całkowicie bezwarunkowe i pozbędzie się wszystkich podwidywań w podanym widoku. Jeśli chcesz coś bardziej drobnoziarnistego, możesz przyjąć dowolne z kilku różnych podejść:

  • utrzymuj własne tablice widoków różnych typów, abyś mógł je później wysyłać removeFromSuperview w ten sam sposób
  • Zachowaj wszystkie swoje poglądy, gdzie tworzysz je i przechowujesz wskaźniki do tych widoków, dzięki czemu możesz je wysłać removeFromSuperview indywidualnie w razie potrzeby
  • Dodaj polecenie if do powyższej pętli, sprawdzając równość klasy. Na przykład, aby usunąć tylko wszystkie Uibuttony (lub niestandardowe podklasy UIButton), które istnieją w widoku, możesz użyć czegoś takiego jak:
// Again, valid UIView *view:
for(UIView *subview in [view subviews]) {
    if([subview isKindOfClass:[UIButton class]]) {
        [subview removeFromSuperview];
    } else {
        // Do nothing - not a UIButton or subclass instance
    }
}
 103
Author: Tim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-21 09:15:36

Stare pytanie; ale jako, że jest to pierwszy hit w Google za to pomyślałem, że też zanotuję, że jest też ta metoda:

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

Nie możesz tego sprawdzić isKindOfClass, ale nadal jest to dobre rozwiązanie, o którym warto wiedzieć.

Edit: kolejnym punktem, który należy zauważyć, jest to, że pasek przewijania widoku przewijania jest dodawany jako subview do tego widoku przewijania. Tak więc, jeśli iterujesz przez wszystkie podviewywii przewijania, natkniesz się na niego. Po usunięciu doda się ponownie-ale to ważne, aby to wiedzieć, jeśli oczekujesz, że będą tam tylko własne podklasy UIView.

Poprawka do Swift 3:

myScrollView.subviews.forEach { $0.removeFromSuperview() }
 37
Author: Wex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-08 10:58:22

Aby dodać do tego, co powiedział Tim, zauważyłem, że tagujesz swoje poglądy. Jeśli chcesz usunąć widok z określonym tagiem, możesz użyć:

[[myScrollView viewWithTag:myButtonTag] removeFromSuperview];
 9
Author: Terry Blanchard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-30 23:31:21

Myślę, że nie powinieneś używać sugestii szybkiego wyliczenia.

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

Czy to nie powinno rzucać wyjątku, jeśli zmienisz kolekcję, która jest iterowana? http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocFastEnumeration.html#//apple_ref/doc/uid/TP30001163-CH18-SW3

Ten przykład może być lepszy.

NSArray *subviews = [[scroller subviews] copy];
for (UIView *subview in subviews) {
    [subview removeFromSuperview];
}
[subviews release];
 8
Author: Coderdad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-02 17:47:21

Problem z podklasą Uiscrollview i in. UIView polega na tym, że początkowo zawierają one niektóre widoki (jak pionowy i poziomy pasek przewijania dla UIScrollView). Więc utworzyłem kategorię UIView, aby usunąć Podview filtrowane na klasie.

Na przykład:

[UIScrollView removeAllSubviewsOfClass:[FooView class],[BarView class],nil];

Kod:

- (void)removeAllSubviewsOfClass:(Class)firstClass, ... NS_REQUIRES_NIL_TERMINATION;


- (void)removeAllSubviewsOfClass:(Class)firstClass, ...
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"FALSEPREDICATE"];

    va_list args;
    va_start(args, firstClass);

    for (Class class = firstClass; class != nil; class = va_arg(args, Class)) 
    {
        predicate = [NSCompoundPredicate orPredicateWithSubpredicates:[NSArray arrayWithObjects:predicate,[NSPredicate predicateWithFormat:@"self isKindOfClass:%@",class], nil]];
    }

    va_end(args);
    [[self.subviews filteredArrayUsingPredicate:predicate] makeObjectsPerformSelector:@selector(removeFromSuperview)];

}
 2
Author: Julien,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-22 11:04:03

Najlepszy i najłatwiejszy jest w użyciu

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

To rzeczywiście powoduje awarię, ponieważ podstawową zasadą jest to, że tablica nie powinna być modyfikowana podczas wyliczania, aby zapobiec temu, że możemy użyć

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

Ale czasami nadal pojawia się awaria, ponieważ makeObjectsPerformSelector: wyliczy i wykona selektor, również w iOS 7 operacje ui są zoptymalizowane tak, aby działały szybciej niż w iOS 6, stąd najlepszy sposób na odwrócenie tablicy i usunięcie

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

Uwaga: wyliczanie szkód modyfikacja, ale nie iteracja...

 1
Author: RamaKrishna Chunduri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-24 10:55:08

Najprostszym i najlepszym sposobem jest

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

     [subview removeFromSuperview];

 }
 0
Author: Shashank Kulshrestha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-16 07:01:06
for(subview) in self.scrollView.subviews {
        subview.removeFromSuperview()
}
 0
Author: johndpope,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-09 00:59:03