麻烦移动UIView

时间:2012-06-07 21:34:51

标签: objective-c xcode ios5

以下文件将一系列形状加载到UIViewController中。每个形状随机放置在屏幕上。我可以使用以下代码水平更改图像的形状,但我不能在UIView上移动图像的x和y坐标。如何将形状移动到屏幕上的其他位置?以下更改了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

1 个答案:

答案 0 :(得分: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)];}];
    }