效果图:

默认情况下通过UIScrollView实现图片轮播。图片间是无缝连接的。

要想实现iOS相册中的间距效果,就需要用到
CGRectInset(CGRect rect, CGFloat dx, CGFloat dy)
这个功能了
subView.frame = CGRectInset(frame, dx, dy);
这里的意思是设置subView的frame为父视图的frame,但是宽缩小dx,高缩小dy
先上代码
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 100, 375, 400)];
_scrollView.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:_scrollView];
[_scrollView setContentSize:CGSizeMake(375 * 9, 0)];
_scrollView.pagingEnabled = YES;
CGFloat dx = 20.0f; //间距,这里指一边,实际效果是两页间的间距加起来,即dx*2
CGFloat itemWidth = _scrollView.bounds.size.width + dx * 2.0; //每个元素所占宽
for (int i = 0; i < 9; i++) {
UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(375 * i, 0, 375, 400)];
subView.backgroundColor = [self arcColor];
[_scrollView addSubview:subView];
CGRect frame = _scrollView.bounds;
frame.origin.x = itemWidth * i;
frame.origin.y = 0;
frame.size.width = itemWidth;
subView.frame = CGRectInset(frame, dx, 0); //缩小至适应屏幕
}
_scrollView.frame = CGRectMake(-dx, 100, itemWidth, 400);
CGSize pageViewSize = _scrollView.bounds.size;
[_scrollView setContentSize:CGSizeMake(itemWidth * 9, pageViewSize.height)]; //将间距计算进size中
}
- (UIColor *)arcColor
{
return [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1];
}
原理:设置scrollView的contentSize.width为默认情况下的width加上增加的间距值
itemWidth是指scrollView上每页的宽度
最后还有一个很重要的功能,
subView.frame = CGRectInset(frame, dx, 0); //缩小至适应屏幕
从该文章中获取到的信息
http://www.mamicode.com/info-detail-506734.html
网友评论