2012-06-07 58 views
0

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

在你moveTheShape方法,你需要设置的框架,没有边界,并在CGRectMake x和y的值设置为大于0

其他的东西你可以得到你原来的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)];}]; 
    } 
+1

的0在他'CGRectMake'指定的的CGRect的左上角应该是在屏幕的左上角,所以他们是完全正常的,并没有:在moveTheShape方法是这样的值被改变。但是,我相信你说OP中必须设置框架而不是'moveTheShape'方法中的边界是正确的。这是因为边界表示相对于它自己的坐标系统的视图的位置和大小,而它的框架是相对于它所在的超视图的坐标系统的位置和大小。 – pasawaya

+0

例如,如果您有位于(0,0)处的视图,它的框架和边界是相等的,但是如果将它向右移动一个像素,则边界仍然是相同的,但框架的x坐标将是一个更大。在这里看到更多的信息:http://stackoverflow.com/questions/1210047/iphone-development-whats-the-difference-between-the-frame-and-the-bounds – pasawaya

+0

完美。谢谢。我可以问你跟进吗?在moveTheShape方法中,我想要连续的形状实例来改变它们的位置(例如,x + = 5)。有没有一个对象允许我提取一个CGRect来让我读取当前的x,y值?我试过\t CGRect oldVals = [(Shape *)timer frame]; int oldX = oldVals.origin.x; int oldY = oldVals.origin.y; 但这给了我一个错误。 – SimonRH