用视图控件 实现简单的跑马灯

一、找到两张图片  分别表示暂停和开始

二、用到全局变量  

 NSTimer *time;

二、具体的代码

 <span style="font-size:18px;">//设置窗口为主窗口
    [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>
<span style="font-size:18px;">  //设置按钮的frame
    startButton.frame = CGRectMake(100, 20, image1.size.width, image2.size.height);
    [self.window addSubview:startButton];
    
    
    //正常状态下按钮显示的图片
    [startButton setImage:image2 forState:UIControlStateNormal];</span>
<span style="font-size:18px;">   // 选中状态下  按钮显示的图片
    [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>
<span style="font-size:18px;">        定时器开始
        time = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(ss) userInfo:nil repeats:YES];
    }
    else{</span>
<span style="font-size:18px;">        处于选中状态的话 如果再触发这个方法  把选中状态改为no  并移除定时器
         sender.selected = NO;
        [time invalidate];
        time = nil;
       
        
    }

}

</span>
<span style="font-size:18px;">//定时器调用的方法  让灯跑的方法
- (void)ss{</span>
<span style="font-size:18px;">    注意数组 </span><span style="font-size: 18px; font-family: Arial, Helvetica, sans-serif;">subviews 里存放的是所有视图  以下2两句是关键语句  注意理解</span><span style="font-size:18px;">

    self.window.subviews[6].backgroundColor = [UIColor blackColor];
    self.window.subviews[1].backgroundColor = [UIColor yellowColor];</span>
<span style="font-size:18px;">    把数组里的第一个元素推到最上面 
    [self.window bringSubviewToFront:self.window.subviews[1]];
}
</span>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值