contentsize、contentoffset 和contentInset 详解
下面我用怎么做一个书架的例子和大家说说contentsize、contentoffset 和contentInset的区别。
NSString *path = nil; UIImage *back = nil; NSString *str = nil; UIImage *aImage = nil; path = [[NSBundle mainBundle] pathForResource:@"shujia" ofType:@"jpg"]; back = [UIImage imageWithContentsOfFile:path];//加载图片 _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(96, 84,back.size.width,back.size.height)]; _scrollView.showsVerticalScrollIndicator = NO; //将竖直方向的滚动条隐藏 //将shujia.jpg作为_scrollerView的背景 UIColor *color=[[UIColor alloc]initWithPatternImage:back]; [_scrollView setBackgroundColor:color]; _buttonList=[NSMutableArray arrayWithCapacity:9]; for(int i=0;i<9;i++) { str=[NSString stringWithFormat:@"menubook%d",i+1]; path = [[NSBundle mainBundle] pathForResource:str ofType:@"png"]; aImage = [UIImage imageWithContentsOfFile:path]; int x = (i%3)* (aImage.size.width+15); int y = (i/3)* (aImage.size.height+30); _whichPeople = [UIButton buttonWithType:UIButtonTypeCustom]; _whichPeople.frame = CGRectMake(x+10,y+30,aImage.size.width,aImage.size.height); _whichPeople.tag = i; [_whichPeople setImage:aImage forState:UIControlStateNormal];//这个图片是在布点击时响应 path = nil; aImage = nil; str = nil; str=[NSString stringWithFormat:@"menubook%d_1",i+1]; path = [[NSBundle mainBundle] pathForResource:str ofType:@"png"]; aImage = [UIImage imageWithContentsOfFile:path]; [_whichPeople setImage:aImage forState:UIControlStateHighlighted];//图片在点击的时候响应 [_whichPeople addTarget:self action:@selector(ButtonClick:) forControlEvents:UIControlEventTouchUpInside]; [_scrollView addSubview:_whichPeople]; [_buttonList addObject:_whichPeople]; path = nil; aImage = nil; str = nil; } //控制可以滚动的区域 _scrollView.contentSize = CGSizeMake(480, 580); //当前显示区域顶点相对于frame顶点的偏移量 _scrollView.contentOffset = CGPointMake(0, 0); //scrollview的contentview的顶点相对于scrollview的位置 _scrollView.contentInset = UIEdgeInsetsMake(0 , 0, 0, 0); [self.view addSubview:_scrollView];
contentSize是scrollview可以滚动的区域,比如frame = (0 ,0 ,320 ,480) contentSize = (320 ,960),代表你的scrollview可以上下滚动,滚动区域为frame大小的两倍。
contentOffset是scrollview当前显示区域顶点相对于frame顶点的偏移量,比如上个例子你拉到最下面,contentoffset就是(0 ,480),也就是y偏移了480
contentInset是scrollview的contentview的顶点相对于scrollview的位置,例如你的contentInset = (0 ,100),那么你的contentview就是从scrollview的(0 ,100)开始显示