[Objective-C] 纯文本查看 复制代码
//
// ViewController.m
// Test
//
// Created by 余西安 on 15/7/1.
// Copyright (c) 2015年 Sian. All rights reserved.
//
#import "ViewController.h"
@interface ViewController () <UIScrollViewDelegate>
@property (nonatomic, assign) BOOL firstAppear;
@property (nonatomic, strong) UIScrollView *scrollView;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.firstAppear = YES;
// 创建基础ScrollView控件
UIScrollView *scrollView = [[UIScrollView alloc] init];
scrollView.pagingEnabled = YES;
scrollView.delegate = self;
// 创建三个子控件并添加到ScrollView(子控件可以是UIView的任何子类,常用的如:UIImageView、UIWebView、UITextView等)
for (int i = 0; i < 3; i++) {
UILabel *label = [[UILabel alloc] init];
label.tag = i + 1;
label.textAlignment = NSTextAlignmentCenter;
label.text = [NSString stringWithFormat:@"%ld", label.tag];
label.font = [UIFont systemFontOfSize:160];
[scrollView addSubview:label];
}
self.scrollView = scrollView;
[self.view addSubview:scrollView];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if (self.firstAppear){
[self viewFirstAppear:animated];
}
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
self.firstAppear = NO;
}
/// 第一次出现该View时调整所有控件位置尺寸
- (void)viewFirstAppear:(BOOL)aninated
{
self.scrollView.frame = self.view.bounds;
CGSize size = self.view.bounds.size;
for (UIView *view in self.scrollView.subviews) {
NSInteger index = view.tag - 1;
// 过滤掉scrollView原有的子控件
if (index < 0) continue;
CGFloat x = index * size.width;
view.frame = (CGRect){x, 0, size};
}
self.scrollView.contentOffset = CGPointMake(size.width, 0);
self.scrollView.contentSize = CGSizeMake(size.width * 3, size.height);
}
/// scrollView停止减速时调用,核心算法在这里!!
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
CGFloat width = scrollView.bounds.size.width;
CGFloat offsetX = scrollView.contentOffset.x;
NSInteger index = offsetX / width;
// 让scrollView再次返回到最中间位置
scrollView.contentOffset = CGPointMake(width, 0);
// index取值为0、1、2分别对应当前为第几个视图
switch (index){
case 0:{ // 往左侧滑(手势往左),所有控件往左移一个单位,出界补最右边
for (UIView *view in self.scrollView.subviews) {
if (view.tag < 1) continue; // 过滤
// 利用tag来决定位置(1、2、3)-> (2、3、1)
view.tag = (view.tag % 3) + 1;
CGFloat x = (view.tag - 0.5) * width;
CGFloat y = view.center.y;
view.center = CGPointMake(x, y);
}
}break;
case 2:{ // 往右侧滑(手势往右),所有控件往右移一个单位,出界补最左边
for (UIView *view in self.scrollView.subviews) {
if (view.tag < 1) continue;
// 利用tag来决定位置(1、2、3)-> (3、1、2)
view.tag = ((view.tag + 1) % 3) + 1;
CGFloat x = (view.tag - 0.5) * width;
CGFloat y = view.center.y;
view.center = CGPointMake(x, y);
}
}break;
default:break;
}
}
@end