当前位置:编程学习 > wap >>

IOS控件的应用UIPageController与UIScrollView

UIPageController是大多数IOS教程上不会写的系统自带控件。它主要的功能是实现视图分页,有点类似于网页上的分页功能。

这次主要通过一个例子来讲讲UIPageController控件和UIScrollView的应用。首先上图:

 淘宝首页截图

图中标有红框的地方,便是UIPageController的展现样式,在xcode里它是这个样子的:


现在要开始使用UIPageController控件了,首先在申明文件顶部添加一个常量,来定义滚图中的子项数量
 

#define
 PAGENUM 4
在类的申明文件(.h)里添加对Page控制器的申明:
 
 
@property
 (strong, nonatomic) IBOutlet UIPageControl *page;

@property
 (strong, nonatomic) IBOutlet UIScrollView *imageScrollView;
然后在实现文件(.m)里添加 对page对象的
 

@synthesize
 page;

@synthesize
 imageScrollView;
实现page对象的自动存取器。
改写viewDidLoad方法如下
 
 (void)viewDidLoad

{

    [super
 viewDidLoad];

    //这里定义了滚动视图的大小,是否支持翻页,是否显示水平滚动标示,委托对象是哪个

    imageScrollView.contentSize
 = CGSizeMake(PAGENUM * 320.0f, imageScrollView.frame.size.height);

    imageScrollView.pagingEnabled
 = YES;

    imageScrollView.showsHorizontalScrollIndicator
 = NO;

    imageScrollView.delegate
 = self;

 

    //这里为滚动视图添加了子视图,为了能添加后续操作,我这里定义的子视图是按键UIButton

    for

(int

i = 0; i < PAGENUM; i++) {

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

        UIButton
 *imageButton = [[UIButton alloc] initWithFrame:CGRectMake(i * 320.0f,  0.0f, 320.0f, 218.0f)];

        [imageButton
 setBackgroundImage:[UIImage imageNamed:fileName] forState:UIControlStateNormal];

        imageButton.tag
 = 900 + i;

        [imageScrollView
 addSubview:imageButton];

    }

 

    //定义PageController
 设定总页数,当前页,定义当控件被用户操作时,要触发的动作。

    page.numberOfPages
 = PAGENUM;

    page.currentPage
 = 0;

    [page
 addTarget:self action:@selector(pageTurn:) forControlEvents:UIControlEventValueChanged];

 

    //使用NSTimer实现定时触发滚动控件滚动的动作。

    timeCount
 = 0;

    [NSTimer
 scheduledTimerWithTimeInterval:5 target:self selector:@selector(scrollTimer) userInfo:nil repeats:YES];

 

}
增加两个翻页动画和自动翻页的函数
 

//滚图的动画效果

-(void)pageTurn:(UIPageControl
 *)aPageControl{

    int

whichPage = aPageControl.currentPage;

    [UIView
 beginAnimations:nil context:NULL];

    [UIView
 setAnimationDuration:0.3f];

    [UIView
 setAnimationCurve:UIViewAnimationCurveEaseInOut];

    [imageScrollView
 setContentOffset:CGPointMake(320.0f * whichPage, 0.0f) animated:YES];

    [UIView
 commitAnimations];

}

 

//定时滚动

-(void)scrollTimer{

    timeCount
 ++;

    if

(timeCount == PAGENUM) {

        timeCount
 = 0;

    }

    [imageScrollView
 scrollRectToVisible:CGRectMake(timeCount * 320.0, 65.0, 320.0, 218.0) animated:YES];

}

补充:移动开发 , IOS ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,