简体   繁体   中英

UIScrollView setContentOffset will add a subview to the scrollview?

I happened to find that setContentOffset to a UIScrollView will cause the scrollView append a new view to its subviews. here is the code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake((320 - 261) / 2, 50, 261, 67)];
    scrollView.pagingEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.bounces = NO;
    scrollView.backgroundColor = [UIColor darkGrayColor];
    for (int i = 0; i < 5; i ++) {
       UIView *view = [[UIView alloc] initWithFrame:CGRectMake(i * 87, 1, 87, 65)];
       view.tag = i;
       UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 50, 30)];
       label.backgroundColor = [UIColor clearColor];
       label.textColor = [UIColor whiteColor];
       label.text = [NSString stringWithFormat:@"%d", i];
       [view addSubview:label];
       view.backgroundColor = [UIColor greenColor];
       [scrollView addSubview:view];
   }
   scrollView.contentSize = CGSizeMake(87 * 5, 67);
   NSLog(@"before scroll: count of subview is %d", scrollView.subviews.count);
   CGPoint offset = CGPointMake(87, 0);
   [scrollView setContentOffset:offset animated:YES];
   NSLog(@"after scroll: count of subview is %d", scrollView.subviews.count);
   [self.view addSubview:scrollView];
}

Before calling setContentOffset:offset , the number of subviews of the scrollView is 5. This is what I expect. After that, the number turns to be 6. Is it working as designed? How to avoid the new subview appended?

The extra subview is the scroll indicator. If you check again in a later method, it will have gone away. Don't worry.

You can confirm this by hiding the scroll indicators ( showsVerticalScrollIndicator and showsHorizontalScrollIndicator properties).

Don't try to assume things about the view hierarchy of UIKit classes. UIKit can, and does, add its own views to several things - see tableviews and their cells, a navigation controller's view and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM