首先,在storyboard拖放滚动视图,将scrollview的出口命名为scrollView。两个数组一个是mutable,一个是immutable。
@property(nonatomic,strong)IBOutlet UIScrollView *scrollView;
@property(nonatomic,strong)NSMutableArray *images;
@property(nonatomic,strong)NSArray *imagesName;
immutable 数组只存储我们想要在滚动视图上显示的图像。确保定义了UIscrollview 委托。
在didload 函数中的viewcontoller.m 文件中执行以下代码:
imagesName = [[NSArray alloc]initWithObjects:@"centipede.jpg",@"ladybug.jpg",@"potatoBug.jpg",@"wolfSpider.jpg", @"ladybug.jpg",@"potatoBug.jpg",@"centipede.jpg",@"wolfSpider.jpg",nil];
// mutable array used to show the images on scrollview dynamic becaus after one
// image when scroll other will come
images = [[NSMutableArray alloc]init];
scrollView.delegate = self;
scrollView.scrollEnabled = YES;
int scrollWidth = 120;
scrollView.contentSize = CGSizeMake(scrollWidth,80);
int xOffset = 0;
//the loop go till all images will load
for(int index=0; index < [imagesName count]; index++)
{
UIImageView *img = [[UIImageView alloc] init];
// make the imageview object because in scrollview we need image
img.frame = CGRectMake(5+xOffset, 0, 160, 110);
// the offset represent the values, used so that topleft for each image will
// change with(5+xOffset, 0)and the bottomright(160, 110)
NSLog(@"image: %@",[imagesName objectAtIndex:index]);
img.image = [UIImage imageNamed:[imagesName objectAtIndex:index]];
// The image will put on the img object
[images insertObject:img atIndex:index];
// Put the img object at the images array which is mutable array
scrollView.contentSize = CGSizeMake(scrollWidth+xOffset,110);
//scroll view size show after 125 width the scroll view enabled
[scrollView addSubview:[images objectAtIndex:index]];
// set images on scroll view
xOffset += 170;
}