您的位置:首页 > 移动开发 > IOS开发

iOS - 关于轮播图的实现实例

2016-12-08 16:45 225 查看
在此,因为只有一个页面,所以没有管理定时器。如果在实际开发项目中,则需要把定时器在合适的位置 kill 掉。本博客只作为一个参考的小 Demo 。。。代码如下:

// 屏幕尺寸

#define    WIDTH       [UIScreen mainScreen].bounds.size.width

#define    HEIGHT      [UIScreen mainScreen].bounds.size.height

// 照片的数量

#define    PHOTOCOUNT  4

// 轮播时间的间隔

#define    MOVETIME    2.0

#import "ViewController.h"

@interface
ViewController () <UIScrollViewDelegate> {

    UIScrollView *_scroll;

    UIPageControl *_page;

}

@end

@implementation ViewController

- (void)viewDidLoad {

    [super
viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    UIScrollView *scrollView = [[UIScrollView
alloc] init];

    scrollView.frame =
self.view.bounds;

    scrollView.backgroundColor = [UIColor
blackColor];

    scrollView.delegate =
self;

    scrollView.pagingEnabled =
YES;

    scrollView.bounces =
NO;

    [self.view
addSubview:scrollView];

    _scroll = scrollView;

    

    UIPageControl *page = [[UIPageControl
alloc]
init];

    page.frame =
CGRectMake((WIDTH-100)/2,
HEIGHT-50,
100, 20);

    page.backgroundColor = [UIColor
blackColor];

    page.numberOfPages =
PHOTOCOUNT;

    page.currentPageIndicatorTintColor = [UIColor
whiteColor];

    page.pageIndicatorTintColor = [UIColor
redColor];

   
da9a
[self.view
addSubview:page];

    _page = page;

    

    

    for (NSInteger i =
0; i<PHOTOCOUNT+1; i++) {

        UIImageView *imageView = [[UIImageView
alloc] init];

        imageView.frame =
CGRectMake(WIDTH*i,
0, WIDTH,
HEIGHT);

        imageView.contentMode =
UIViewContentModeScaleAspectFit;

        NSString *name = [NSString
stringWithFormat:@"%ld.jpg",i];

        if (PHOTOCOUNT == i) {

            name = @"0.jpg";

        }

        imageView.image = [UIImage
imageNamed:name];

        [scrollView addSubview:imageView];

 

    }

    

    scrollView.contentSize =
CGSizeMake(WIDTH*(PHOTOCOUNT+1),
0);

    

    NSTimer *timer = [NSTimer
timerWithTimeInterval:MOVETIME
target:self
selector:@selector(movePhoto)
userInfo:nil
repeats:YES];

    

    [[NSRunLoop
currentRunLoop] addTimer:timer
forMode:NSRunLoopCommonModes];

    

}

- (void)movePhoto {

    

    NSInteger contentOffSet_x =
_scroll.contentOffset.x;

    

    if (contentOffSet_x >=
PHOTOCOUNT*WIDTH) {

        

        [_scroll
setContentOffset:CGPointMake(0,
0) animated:NO];

        _page.currentPage =
0;

    }else {

        

        [_scroll
setContentOffset:CGPointMake(contentOffSet_x+WIDTH,
0) animated:YES];

        _page.currentPage =
_scroll.contentOffset.x/WIDTH
+ 1;

    }

    

    if (contentOffSet_x == (PHOTOCOUNT-1)*WIDTH)
{

        _page.currentPage =
0;

    }

    

}

OK,一个简易的轮播图就到此结束。。。







内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: