天天看點

(5.19)scrollview的分頁滾動

#import

"mainController.h"

@interface

mainController ()

//分頁控件

@property(nonatomic,weak)UIPageControl

*pageController;

//滾動視圖

@property(nonatomic,weak)UIScrollView

*scrollder;

@end

@implementation mainController

//開發步驟

//1,搭建ui界面,建立scrollview

//2,增加分頁功能

//3,添加分頁控件

-(void)loadView{

    //1,執行個體化視圖view

self.view = [[UIView alloc]initWithFrame:[UIScreen

mainScreen].applicationFrame];

//2,建立滾動視圖

UIScrollView *scroll = [[UIScrollView

alloc]initWithFrame:self.view.bounds];

    //3,将scroll加載到目前視圖

    [self.view

addSubview:scroll];

    //4,初始化資料

NSMutableArray *array = [[NSMutableArray

alloc]initWithCapacity:5];

    for (NSInteger i = 0; i < 5; i++)

{

//建立圖檔的檔案名

        NSString

*imageName = [NSString stringWithFormat:@"%d.jpg",i+1];

//建立圖像視圖

        UIImage

*images = [UIImage imageNamed:imageName];

        UIImageView

*imageView = [[UIImageView alloc]initWithImage:images];

//将視圖添加到數組

        [array

addObject:imageView];

        CGFloat

width = scroll.bounds.size.width;

//将建立好的數組添加到scrollView

enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)

//1,從數組中取出imageView

UIImageView *imageView = obj;

//2,設定圖像視圖的frame

[imageView setFrame:CGRectMake(width * idx, 0, width,

scroll.bounds.size.height)];

//3,将圖像視圖添加到scroller

[scroll addSubview:imageView];

}];

//設定滾動視圖屬性

//1,設定滾動區域

        [scroll

setContentSize:CGSizeMake(scroll.bounds.size.width * 5,

scroll.bounds.size.width)];

//2,允許分頁

setPagingEnabled:YES];

//3,關閉彈簧效果

setBounces:NO];

//4,關閉水準滾動條

setShowsHorizontalScrollIndicator:NO];

//設定滾動視圖代理

setDelegate:self];

//添加分頁控件

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

//根據指定的頁數,傳回分頁控件的大小

        CGSize size

= [pageControl sizeForNumberOfPages:5];

        [pageControl

setFrame:CGRectMake(0, 0, size.width, size.height)];

//設定分頁控件的位子

setCenter:CGPointMake(width / 2 , 400)];

//設定分頁控件的頁數

setNumberOfPages:5];

setCurrentPage:0];

//設定分頁控件的顔色

setCurrentPageIndicatorTintColor:[UIColor redColor]];

[pageControl setPageIndicatorTintColor:[UIColor blackColor]];

//添加到視圖

        [self.view

addSubview:pageControl];

self.pageController =pageControl;

self.scrollder = scroll;

//添加分頁空間的監聽方法

addTarget:self action:@selector(pageChange:)

forControlEvents:UIControlEventValueChanged];

}

#pragma

mark - uiscrollview代理方法

#pragma mark

滾動停止事件

-(void)scrollViewDidEndDecelerating:(UIScrollView

*)scrollView{

NSLog(@"滾動停止");

//根據scrollview的方法,判斷頁數

    NSInteger pageNo =

scrollView.contentOffset.x / scrollView.bounds.size.width;

    [self.pageController

setCurrentPage:pageNo];

設定分頁控件的監聽方法

-(void)pageChange:(UIPageControl

*)sender{

NSLog(@"分頁控件被點選");

//判斷目前的控件數

    CGFloat

offsetX = sender.currentPage * self.scrollder.bounds.size.width;

    [self.scrollder

setContentOffset:CGPointMake(offsetX, 0) animated:YES];