编辑:
创建一个名为“ImageSliderViewController”的新视图控制器并将此代码复制到 ImageSliderViewController.m 文件中,并将附加的图像添加到项目中。
#import "ImageSliderViewController.h"
@interface ImageSliderViewController ()
{
int intMaxLength,intStartPosition;
UIScrollView *imageSlider;
NSTimer *timerForImageSlider;
}
@end
@implementation ImageSliderViewController
- (void)viewDidLoad
{
[super viewDidLoad];
imageSlider = [[UIScrollView alloc]initWithFrame:CGRectMake(25, 20, 270, 180)];
[self.view addSubview:imageSlider];
[imageSlider setContentOffset:CGPointMake(0, 0) animated:YES];
[imageSlider setShowsHorizontalScrollIndicator:NO];
[imageSlider setScrollEnabled:NO];
NSArray *imagesArray = [[NSArray alloc]initWithObjects:[UIImage imageNamed:@"1.png"] ,
[UIImage imageNamed:@"2.png"] ,
[UIImage imageNamed:@"3.png"] ,
[UIImage imageNamed:@"4.png"] ,
nil];
[imageSlider setContentSize:CGSizeMake([imagesArray count]*270, 180)];
intMaxLength = [imagesArray count] * 270;
int xPosition = 0;
for(int i = 0 ; i < [imagesArray count] ; i++)
{
UIImageView *ivImage = [[UIImageView alloc] initWithFrame:CGRectMake(xPosition, 0, 270, 180)];
ivImage.image = [imagesArray objectAtIndex:i];
[imageSlider addSubview:ivImage];
xPosition += 270;
}
intStartPosition = 0;
UISwipeGestureRecognizer *recognizer;
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
[[self view] addGestureRecognizer:recognizer];
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
[[self view] addGestureRecognizer:recognizer];
timerForImageSlider = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(imageSlider) userInfo:nil repeats:YES];
}
-(IBAction)handleSwipeFrom:(UISwipeGestureRecognizer*)sender
{
if (sender.direction == UISwipeGestureRecognizerDirectionLeft)
{
if(intMaxLength <=intStartPosition+270 )
{
return;
}
else
{
intStartPosition += 270;
[imageSlider setContentOffset:CGPointMake(intStartPosition,0) animated:YES];
}
}
else if(sender.direction == UISwipeGestureRecognizerDirectionRight)
{
if(0 > intStartPosition-270 )
{
return;
}
else
{
intStartPosition -= 270;
[imageSlider setContentOffset:CGPointMake(intStartPosition,0) animated:YES];
}
}
}
-(void)imageSlider
{
if(intMaxLength <=intStartPosition+270 )
{
[imageSlider setContentOffset:CGPointMake(0,0) animated:YES];
intStartPosition = 0;
}
else
{
intStartPosition += 270;
[imageSlider setContentOffset:CGPointMake(intStartPosition,0) animated:YES];
}
}
@end
图片在这里::::