你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS 輪播圖實現

iOS 輪播圖實現

編輯:IOS開發綜合

 

#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) NSTimer * 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];
[[NSRunLoop 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 = @輪播圖;
[self setView];
}

 

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved