#import "ViewController.h"
#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define kImgW (kScreenW-60)
@interface ViewController ()<UIScrollViewDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/*_________ UIScrollView 滑动视图 ______________________________________________________*/
//1⃣️创建
UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 20, kScreenW,kScreenW)];
scrollView.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:scrollView];
//1.内容尺寸
scrollView.contentSize = CGSizeMake(5 * kImgW, kScreenW);
//5.是否开启首尾反弹效果 默认YES
//滑动
scrollView.bounces = YES;
scrollView.delegate = self;
//获取图片
for (int i = 0; i<5; i++) {
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"scene%d.jpg",i+1]];
UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(i * kImgW, 0, kImgW, kScreenW)];
imageV.image = image;
imageV.layer.borderColor = [[UIColor purpleColor]CGColor];
//边框的宽度
imageV.layer.borderWidth = 1;
//圆角
imageV.layer.cornerRadius = 30.0;
//是否开启裁剪
imageV.clipsToBounds = YES;
[scrollView addSubview:imageV];
}
UIView *redView = [[UIView alloc]initWithFrame:CGRectMake(kScreenW/2, 0, 1, kScreenH)];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
/*_______________________________________________________________*/
//因为图片宽度比控件宽度短 为了让首位图片显示在控件中间 所以添加
scrollView.contentInset = UIEdgeInsetsMake(0, 30, 0, 30);
//滑动视图一开始显示 第一张图片就在中间
scrollView.contentOffset = CGPointMake(-30, 0);
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
[self customPage:scrollView];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
[self customPage:scrollView];
}
/**
* 自定义的分页方法
*/
- (void)customPage:(UIScrollView *)scrollView{
//1.获取当前偏移量 根据偏移量计算出应该显示的item的index
NSInteger index = (scrollView.contentOffset.x + kImgW/2)/kImgW;
NSLog(@"%ld",index);
//2.通过index设置新的滑动偏移量
// scrollView.contentOffset = CGPointMake(index * kImgW, 0);
[scrollView setContentOffset:CGPointMake(index * kImgW - 30.0, 0) animated:YES];
}
@end
![Uploading 屏幕快照 2016-03-04 下午7.21.33_759992.png . . .]