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

来源:互联网 发布:淘宝上签证怎么办理 编辑:程序博客网 时间:2024/05/02 04:46

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

二、用到全局变量  

 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
原创粉丝点击