下面我用怎麼做一個書架的例子和大家說說contentsize、contentoffset 和contentInset的區別。
[plain]
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)開始顯示
摘自 ComeOnTom的專欄