iOS中实现心块的颜色轮转(重点:交换颜色,设置定时器)

  
    UIView *view5 = [[UIView alloc] initWithFrame:CGRectMake(80, 280, 30, 30)];
    view5.backgroundColor = [UIColor redColor];
     view5.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1.0];
    view5.tag = 105;
    [self.window addSubview:view5];
    [view5 release];
    UIView *view6 = [[UIView alloc] initWithFrame:CGRectMake(40, 240, 30, 30)];
    view6.backgroundColor = [UIColor redColor];
     view6.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1.0];
    view6.tag = 106;
    [self.window addSubview:view6];
    [view6 release];
    
    
    
    
    
    //布局按钮
    UIButton *starbtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [starbtn setTitle:@"开始" forState:UIControlStateNormal];
    
    starbtn.frame = CGRectMake(100, 380, 45, 35);
    [self.window addSubview:starbtn];
    
  
    
    
    UIButton *overbtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [overbtn setTitle:@"取消" forState:UIControlStateNormal];
    
    overbtn.frame = CGRectMake(180, 380, 45, 35);
    [self.window addSubview:overbtn];
  
    
    
    [starbtn addTarget:self action:@selector(startAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [overbtn addTarget:self action:@selector(cancleAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}
- (void)startAction:(UIButton *)sender
{
    //timeInterInterval  时间间隔
    //target 目标
    //seclctor  target要执行selector方法
    //userInfo 用户信息
    //repeats 是否反复定时执行
    [self.timer invalidate];  //取消上一个定时器
   self.timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(changeColor) userInfo:nil repeats:YES];
}
- (void)cancleAction
{

    [self.timer setFireDate:[NSDate distantFuture]];
}

//颜色交换
-(void)changeColor{
    UIView *tempView = [[UIView alloc] init];
    tempView.backgroundColor = [self.window viewWithTag:100].backgroundColor;
    
    for (int i = 100; i < 106; i++) {
        [self.window viewWithTag:i].backgroundColor = [self.window viewWithTag:( i + 1) ].backgroundColor;
    }
    [self.window viewWithTag:106].backgroundColor = tempView.backgroundColor;
}
原文地址:https://www.cnblogs.com/wohaoxue/p/4764707.html