IOS carousel image implementation
# Define SCREEN_SIZE [UIScreen mainScreen]. bounds. size
# Define KImageCount 3
# Define KImage_Height 250
@ Interface ViewController ()
@ Property (nonatomic, strong) UIScrollView * scrollView;
@ Property (nonatomic, strong) UIPageControl * pageControl;
@ Property (nonatomic, strong) nstmer * timer;
@ End
@ Implementation ViewController
-(UIScrollView *) scrollView {
If (_ scrollView = nil ){
_ ScrollView = [[UIScrollView alloc] initWithFrame: CGRectMake (0, 0, SCREEN_SIZE.width, KImage_Height)];
_ ScrollView. pagingEnabled = YES;
_ ScrollView. showsHorizontalScrollIndicator = NO;
}
Return _ scrollView;
}
-(UIPageControl *) pageControl {
If (_ pageControl = nil ){
_ PageControl = [[UIPageControl alloc] initWithFrame: CGRectMake (0, self. scrollView. frame. size. height-30, SCREEN_SIZE.width, 20)];
_ PageControl. currentPageIndicatorTintColor = [UIColor colorWithRed: 65/255 .0 green: 168/255 .0 blue: 100/255. 0 alpha: 1.0];
_ PageControl. pageIndicatorTintColor = [UIColor grayColor];
}
Return _ pageControl;
}
-(Void) setView {
[Self. view addSubview: self. scrollView];
[Self. view addSubview: self. pageControl];
CGFloat imageY = 0;
CGFloat imageW = SCREEN_SIZE.width;
CGFloat imageH = KImage_Height;
For (int I = 0; I <KImageCount; I ++ ){
UIImageView * imageView = [[UIImageView alloc] initWithFrame: CGRectMake (I * imageW, imageY, imageW, imageH)];
ImageView. image = [UIImage imageNamed: [NSString stringWithFormat: @ % I .jpg, I + 1];
[Self. scrollView addSubview: imageView];
}
Self. scrollView. contentSize = CGSizeMake (KImageCount * imageW, 0 );
Self. scrollView. delegate = self;
Self. pageControl. numberOfPages = KImageCount;
[Self addTimer];
}
-(Void) addTimer {
Self. timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self selector: @ selector (nextImage) userInfo: nil repeats: YES];
[[Nsunloop mainRunLoop] addTimer: self. timer forMode: NSDefaultRunLoopMode];
}
-(Void) nextImage {
Int I = (int) self. pageControl. currentPage;
If (I = KImageCount-1 ){
I =-1;
}
I ++;
[Self. scrollView setContentOffset: CGPointMake (I * self. scrollView. frame. size. width, 0) animated: YES];
}
-(Void) scrollViewWillBeginDragging :( UIScrollView *) scrollView {
[Self turnOffTimer];
}
-(Void) scrollViewDidEndDragging :( UIScrollView *) scrollView willDecelerate :( BOOL) decelerate {
[Self addTimer];
}
-(Void) turnOffTimer {
[Self. timer invalidate];
Self. timer = nil;
}
-(Void) scrollViewDidScroll :( UIScrollView *) scrollView {
Self. pageControl. currentPage = (self. scrollView. frame. size. width * 0.5 + self. scrollView. contentOffset. x)/self. scrollView. frame. size. width;
}
-(Void) viewDidLoad {
[Super viewDidLoad];
Self. title = @ carousel image;
[Self setView];
}