for loops, for…in loops, random numbers (Xcode for iOS)


While the video isn't that exciting, in programming sometimes we want random things to happen to add texture and variety, and for this purpose loops are ideal. So here's a short piece of code that can be cut and pasted into your view controller .m file, and each time you run it what appears will be different in subtle ways:


// Method for creating random numbers between zero and the number sent 
-(int)randomNumbers:(int)range
{int a = arc4random_uniform(range+1);
    return a;}


- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor blackColor];
    
    // Create a number of UIView objects using a for loop and random numbers to determine the size and position, giving them each a tag for identification later
    
    int i = 0;    
    for (i=0; i<=20; i++)
    {
        int random = [self randomNumbers:10]; 
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10*i*random, 10*i*random, i*random/2, i*random/2)];
        [view setTag:i];
        [self.view addSubview:view];

    };
    
   // Create an array of the subviews created in the for loop
        
    NSArray *subviews = [self.view subviews];
    i=0;  
    
    // Use a for...in loop to animate and colour the UIView objects - setting the length of their animation duration based on  
    for (UIView* v in subviews) {
       
        
        if (i%3==0) {        
            v.backgroundColor=[UIColor yellowColor];
            [UIView animateWithDuration:[v tag]-1 delay:1 options:UIViewAnimationOptionAutoreverse + UIViewAnimationOptionRepeat animations:^{v.transform=CGAffineTransformMakeRotation(150);} completion:nil];
        }
        else if (i%2==0) {        
v.backgroundColor=[UIColor blueColor];
        [UIView animateWithDuration:[v tag]-1 delay:1 options:UIViewAnimationOptionAutoreverse + UIViewAnimationOptionRepeat animations:^{v.transform=CGAffineTransformMakeScale(1.5, 1.5);} completion:nil];
        }
        else {
            v.backgroundColor=[UIColor redColor];
            [UIView animateWithDuration:[v tag]-1 delay:1 options:UIViewAnimationOptionAutoreverse + UIViewAnimationOptionRepeat animations:^{v.transform=CGAffineTransformMakeTranslation(500, 200);} completion:nil];            
        }
    
    i++;}
    
    
    
    
}


It incorporates generating random numbers, view tags, (block-based) view animation and transforms.

Comments