直接在VC.m里面 上代码:
//
// ViewController.m
// 课堂练习 - 滚动视图
//
// Created by shc on 2018/5/24.
// Copyright © 2018年 MacBook. All rights reserved.
//
#import “ViewController.h”
#define hcWidth self.view.frame.size.width
#define hcHeight self.view.frame.size.height
@interface ViewController ()
{
UIScrollView *scV;// 滚动视图
UIPageControl *pgC; // 滚动豆豆
NSTimer *timer; // 定时器
int k;// 计数器
}
@end
@implementation ViewController
-
(void)viewDidLoad {
[super viewDidLoad];timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(aaa) userInfo:nil repeats:YES];
// 1.初始化滚动视图
scV = [[UIScrollView alloc]initWithFrame:self.view.frame];
scV.backgroundColor = [UIColor redColor];
// 设置分页效果
scV.pagingEnabled = YES;
// 禁用水平滚动条
scV.showsHorizontalScrollIndicator = NO;
// 禁用弹簧效果
scV.bounces = NO;[self.view addSubview:scV];
// 2.设置滚动范围
scV.contentSize = CGSizeMake(4 * hcWidth , 0);// 设置代理 为了获取滚动视图的偏移量
scV.delegate = self;// 3. 创建图片视图
for (int i = 0; i < 4; i++){NSArray *arr = @[@"1",@"2",@"3",@"4"]; UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(i *hcWidth, 0, hcWidth, hcHeight)]; imgV.image = [UIImage imageNamed:arr[i]]; // 设置用户交互属性 imgV.userInteractionEnabled = YES; if(i == 3){ UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(150, 550, 100, 80)]; btn.backgroundColor = [UIColor redColor]; [btn addTarget:self action:@selector(abc) forControlEvents:UIControlEventTouchUpInside]; [imgV addSubview:btn]; } [scV addSubview:imgV];
}
// 初始化豆豆
pgC = [[UIPageControl alloc]initWithFrame:CGRectMake(150, 660, 100, 30)];
pgC.numberOfPages = 4;// 选中豆豆的颜色
pgC.currentPageIndicatorTintColor = [UIColor greenColor];
// 豆豆的颜色
pgC.pageIndicatorTintColor = [UIColor blackColor];pgC.currentPage = 0;
[self.view addSubview:pgC];
}
// 视图已经滚动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
NSLog(@"%lf",scV.contentOffset.x);
//将滚动视图的偏移量除以屏幕的宽度赋值给豆豆
pgC.currentPage = scV.contentOffset.x/hcWidth;
}
-(void)abc{
// 跳转
}
-(void)aaa{
[scV setContentOffset:CGPointMake(k *hcWidth, 0)];
k++;
if(k >3){
// [timer invalidate]; // 到最后一个停止
k= 0;// 循环
}
}
@end