大家可以看到大部分APP首页会有图片自动滚动,其中运用到的知识就有滚动视图UIScrollView,分页UIPageControl,还有就是定时器NSTime了.具体代码如下:
#import <UIKit/UIKit.h>
@interface UIScrollViewCell :UITableViewCell<UIScrollViewDelegate>
{
UIScrollView * _scrollView;
UIPageControl * _pageControl;
}
@end
#import "UIScrollViewCell.h"
@implementation UIScrollViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [superinitWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
[selfcreateSubViews];
}
returnself;
}
- (void)createSubViews
{
_scrollView = [[UIScrollViewalloc]initWithFrame:CGRectMake(0,0, 320,150)];
_scrollView.backgroundColor = [UIColorredColor];
[self.contentViewaddSubview:_scrollView];
[_scrollViewrelease];
_scrollView.delegate =self;
_scrollView.contentSize =CGSizeMake(320*3,150);
for (int i =0 ; i<3; i++) {
UIImageView * imageView = [[UIImageViewalloc]initWithFrame:CGRectMake(320*i,0, 320,150)];
UIImage * image = [UIImageimageNamed:[NSString stringWithFormat:@"h%d.jpeg",i+1]];
imageView.image = image;
[_scrollViewaddSubview:imageView];
[imageView release];
NSLog(@"--------------scrollView = %@",_scrollView);
}
_pageControl = [[UIPageControlalloc]initWithFrame:CGRectMake(150,100, 50,50)];
[self.contentViewaddSubview:_pageControl];
// pageControl.backgroundColor = [UIColor greenColor];
_pageControl.numberOfPages =3;
_pageControl.pageIndicatorTintColor = [UIColorblackColor];
_pageControl.currentPageIndicatorTintColor = [UIColorredColor];
[_pageControladdTarget:selfaction:@selector(didClickPageControlAction:)forControlEvents:UIControlEventValueChanged];
[NSTimerscheduledTimerWithTimeInterval:2target:selfselector:@selector(scrollTimer)userInfo:nilrepeats:YES];
}
- (void)didClickPageControlAction:(UIPageControl *)pageControl
{
NSInteger currentPageNumber = pageControl.currentPage;
CGPoint offset =_scrollView.contentOffset;
offset.x = currentPageNumber *320;
[_scrollViewsetContentOffset:offset animated:YES];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
CGFloat offSetX = scrollView.contentOffset.x;
CGFloat pageWidth =320;
NSInteger pageNumber = offSetX/pageWidth;
_pageControl.currentPage = pageNumber;
}
//设置定时器
//这个地方我想了好久,有一个逻辑过程就是,当分页的时候X坐标也跟着变,第一次是0,第二次是320,第三次是320*2,第四次又是0,第五次又是320,第六次又是320*2;故如下所写.
//还有一点就是关于UIScrollView的方法
根据内容的Frame属性,设置可视区域(visible area)
[scrollView scrollRectToVisible:CGRectMake(index*SceneWidth, 0, SceneWidth, SceneHeight) animated:YES];
后面的参数是可视区域的Frame属性,我们也可以这样理解,这个方法就是把UIScrollview的视图区域,移动到指定
Frame的可见区域。
int i = 0;
- (void)scrollTimer
{
i++;
if (i ==4 ) {
i = 0;
}
[_scrollViewscrollRectToVisible:CGRectMake(i*320,0, 320,150) animated:YES];
_pageControl.currentPage =i;
NSLog(@"i= %d",i);
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end