简体   繁体   English

UIScrollView setContentOffset会在scrollview中添加子视图吗?

[英]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. 我碰巧发现setContentOffset到UIScrollView将导致scrollView将新视图附加到其子视图。 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. 在调用setContentOffset:offset之前,scrollView的子视图数是5.这就是我所期望的。 After that, the number turns to be 6. Is it working as designed? 之后,数字变为6.它是否按设计工作? 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). 您可以通过隐藏滚动指示符( showsVerticalScrollIndicatorshowsHorizontalScrollIndicator属性)来确认这一点。

Don't try to assume things about the view hierarchy of UIKit classes. 不要试图假设有关UIKit类的视图层次结构的事情。 UIKit can, and does, add its own views to several things - see tableviews and their cells, a navigation controller's view and so on. UIKit可以并确实将自己的视图添加到几个方面 - 请参阅tableviews及其单元格,导航控制器的视图等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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