您的位置:首页 > 产品设计 > UI/UE

UIKit框架-高级控件:3.UIScrollView的多图分页设置

2015-03-01 13:43 423 查看
在前面我们学会了如何给UIScrollView的单图分页, 下面让我们来看看, 如何给UIScrollView多图分页.

1.设置代理以及设置全局变量

.h文件

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIScrollViewDelegate>

@end
.m文件
@interface ViewController ()
{
UIScrollView *_scrollView;
UIPageControl *_pageControl;
}
@end


2.实例化UIScrollView
- (void)myScrollView
{
// 1.实例化UIScrollView
_scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 28, self.view.frame.size.width, self.view.frame.size.height)];

CGFloat width = _scrollView.bounds.size.width;
CGFloat height = _scrollView.bounds.size.height;

// 2.添加Image内容
for (NSUInteger i = 1; i <= 5; i++) {

NSString *imageFile = [NSString stringWithFormat:@"%ld.jpg", i];
UIImage *image = [UIImage imageNamed:imageFile];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

[imageView setFrame:CGRectMake((i - 1) * width, 0, width, height)];

[_scrollView addSubview:imageView];
}

[_scrollView setBounces:NO];
[_scrollView setShowsHorizontalScrollIndicator:NO];
[_scrollView setContentSize:CGSizeMake(5 * width, height)];

[_scrollView setPagingEnabled:YES];

[self.view addSubview:_scrollView];

[_scrollView setDelegate:self];
}

3.添加UIScrollView的代理方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
CGFloat pageNo = scrollView.contentOffset.x / scrollView.bounds.size.width;
[_pageControl setCurrentPage:pageNo];
}


4.添加UIPageControl
- (void)myPageControl
{
_pageControl = [[UIPageControl alloc] init];
[_pageControl setBounds:CGRectMake(0, 0, 150, 50)];
[_pageControl setCenter:CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height - 50)];

[_pageControl setNumberOfPages:5];
[_pageControl setCurrentPage:0];

[_pageControl setCurrentPageIndicatorTintColor:[UIColor redColor]];
[_pageControl setPageIndicatorTintColor:[UIColor greenColor]];

[_pageControl addTarget:self action:@selector(updatePageChanged:) forControlEvents:UIControlEventValueChanged];

[self.view addSubview:_pageControl];
}


5.添加UIPageControl的坚挺方法
- (void)updatePageChanged:(UIPageControl *)pageControl
{
CGFloat offsetX = pageControl.currentPage * _scrollView.bounds.size.width;

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


6.最后把所有方法都实现
- (void)viewDidLoad {
[super viewDidLoad];
[self myScrollView];
[self myPageControl];
}


下面让我们来看看最终效果:











好了, 这次我们就讲到这里, 下次我们继续~~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: