小项目
一、找到两张图片 分别表示暂停和开始
二、用到全局变量
NSTimer *time;
二、具体的代码
- //设置窗口为主窗口
- [self.window makeKeyAndVisible];
- // 通过for循环创建5个view
- for (int i=0; i<5; i++) {
- UIView *view = [[UIView alloc]initWithFrame:CGRectMake(i*60+30, 400, 50, 50)];
- view.backgroundColor = [UIColor blackColor];
- [self.window addSubview:view];
- }
- // 初始化图片视图并赋值图片
- UIImage *image1 = [UIImage imageNamed:@"start"];
- UIImage *image2 = [UIImage imageNamed:@"stop"];
- //初始化一个按钮
- UIButton *startButton = [UIButton buttonWithType: UIButtonTypeCustom];</span>
//设置按钮的frame
- startButton.frame = CGRectMake(100, 20, image1.size.width, image2.size.height);
- [self.window addSubview:startButton];
- //正常状态下按钮显示的图片
- [startButton setImage:image2 forState:UIControlStateNormal];</span>
- // 选中状态下 按钮显示的图片
- [startButton setImage:image1 forState:UIControlStateSelected];
- 给按钮设置触发事件
- [startButton addTarget:self action:@selector(stop:) forControlEvents:UIControlEventTouchDown];
- 触发事件调用的方法
- - (void)stop:(UIButton *)sender{
- 如果按钮处于未选中状态
- if (sender.selected != YES) {
- 改成选中状态
- sender.selected = YES ;</span>
- 定时器开始
- time = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(ss) userInfo:nil repeats:YES];
- }
- else{
- 处于选中状态的话 如果再触发这个方法 把选中状态改为no 并移除定时器
- sender.selected = NO;
- [time invalidate];
- time = nil;
- }
- }
- //定时器调用的方法 让灯跑的方法
- - (void)ss{
注意数组 subviews 里存放的是所有视图 以下2两句是关键语句 注意理解
- self.window.subviews[6].backgroundColor = [UIColor blackColor];
- self.window.subviews[1].backgroundColor = [UIColor yellowColor];</span>
把数组里的第一个元素推到最上面
- [self.window bringSubviewToFront:self.window.subviews[1]];
- }