0

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
4

1 に答える 1

1

moveTheShape メソッドでは、境界ではなくフレームを設定し、CGRectMake の x 値と y 値を 0 以外に設定する必要があります。

次のように moveTheShape メソッドで元の x 値と y 値を取得できます。

 -(void) moveTheShape:(NSTimer*)timer {
        CGRect frame = [timer.userInfo frame];
        float frameX = frame.origin.x;
        float frameY = frame.origin.y;
        NSLog(@"X component is:%f   Y component is:%f",frameX,frameY);
        [UIView animateWithDuration:0.5f animations:^{[[timer userInfo] setFrame:CGRectMake(200, 100, 5, 5)];}];
    }
于 2012-06-07T21:59:35.110 に答える