The following files load a series of shapes into a UIViewController. Each shape is placed randomly on the screen. I can use the following code to change the shape of the image horizontally, but I cannot move the x and y coordinates of the image on the UIView. How can I move the shape to a different location on screen? The following changes the width of the UIView:
[UIView animateWithDuration:0.5f animations:^{[[timer userInfo] setBounds:CGRectMake(0, 0, 100, 5)];}];
ViewController.h
#import <UIKit/UIKit.h>
#import "Shape.h"
@interface ViewController : UIViewController
@end
ViewController.m
#import "ViewController.h"
@implementation ViewController
UIView *box;
int screenHeight;
int screenWidth;
int x;
int y;
Shape * shape;
- (void)viewDidLoad
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
screenHeight = screenRect.size.height;
screenWidth = screenRect.size.width;
box = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 5)];
[self.view addSubview:box];
for (int i = 0; i<3; i++) {
x = arc4random() % screenWidth;
y = arc4random() % screenHeight;
shape =[[Shape alloc] initWithX:x andY:y];
[box addSubview:shape];
[NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(moveTheShape:) userInfo:shape repeats:YES];
}
}
-(void) moveTheShape:(NSTimer*)timer
{
//[UIView animateWithDuration:0.5f animations:^{[[timer userInfo] setBounds:CGRectMake(100, 0, 100, 5)];}];
[UIView animateWithDuration:0.5f animations:^{[[timer userInfo] setBounds:CGRectMake(0, 0, 100, 5)];}];
}
@end
Shape.h
#import <UIKit/UIKit.h>
@interface Shape : UIView;
- (id) initWithX: (int)xVal andY: (int)yVal;
@end
Shape.m
#import "Shape.h"
@implementation Shape
- (id) initWithX:(int )xVal andY:(int)yVal {
self = [super initWithFrame:CGRectMake(xVal, yVal, 5, 5)];
self.backgroundColor = [UIColor redColor];
return self;
}
@end