UIPageController是大多数IOS教程上不会写的系统自带控件。它主要的功能是实现视图分页,有点类似于网页上的分页功能。
这次主要通过一个例子来讲讲UIPageController控件和UIScrollView的应用。首先上图:
图中标有红框的地方,便是UIPageController的展现样式,在xcode里它是这个样子的:
现在要开始使用UIPageController控件了,首先在申明文件顶部添加一个常量,来定义滚图中的子项数量
|
1
|
#define PAGENUM 4
|
在类的申明文件(.h)里添加对Page控制器的申明:
|
1
2
|
@property (strong, nonatomic) IBOutlet UIPageControl *page;
@property (strong, nonatomic) IBOutlet UIScrollView *imageScrollView;
|
然后在实现文件(.m)里添加 对page对象的
|
1
2
|
@synthesize page;
@synthesize imageScrollView;
|
实现page对象的自动存取器。
改写viewDidLoad方法如下
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
- (
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];
}
|
增加两个翻页动画和自动翻页的函数
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//滚图的动画效果
-(
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];
}
|

本文探讨了UIPageController在iOS开发中的应用,它用于实现视图分页效果,类似网页分页。通过实例,展示了如何结合UIScrollView进行使用,并提供了在Xcode中的设计展示。

1835

被折叠的 条评论
为什么被折叠?



