2011-07-03 30 views
1

如何拖动UIImageView,但只能在屏幕的某个区域内操作?我的代码目前看起来像这样:在受限范围内拖动UIImageView

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ 
    UITouch *touch = [[event allTouches] anyObject]; 
    touch.view.frame = CGRectMake(104, 171, 113, 49); 

    if([touch view] == toggle) 
    { 

     CGPoint location = [touch locationInView:self.view]; 
     CGPoint newLocation = CGPointMake(toggle.center.x, location.y); 

     toggle.center = newLocation; 
     NSLog(@"%f \n",toggle.center.y); 

    } 
} 

我想只能在我定义的框架内拖动图像。

回答

1

您可以使用CGRectContainsRect(rect1, rect2)检查第一矩形是完全内部的第二

bool CGRectContainsRect (
    CGRect rect1, 
    CGRect rect2 
); 

的当您使用UIViews,想看看一个观点完全落在第二的框架内,一个相关的函数CGRectContainsRect将会为你做检查。这不检查交叉点;两个矩形的联合必须等于第一个矩形才能返回true。该函数有两个参数。第一个矩形总是周围的物品。第二个论点要么完全落入第一个,要么不是。

所以,你的代码可能是这样的

CGPoint location = [touch locationInView:self.view]; 
CGPoint newLocation = CGPointMake(toggle.center.x, location.y); 

CGRect r = CGRectMake(newLocation.x-self.frame.size.width/2, 
         newLocation.y-self.frame.size.height/2, 
         self.frame.size.width, 
         self.frame.size.height); 
if(CGRectContainsRect(r, theOtherRect)){ 
    toggle.center = newLocation; 
    NSLog(@"%f \n",toggle.center.y); 
} 

其他有用的功能CoreGraphics的:http://blogs.oreilly.com/iphone/2008/12/useful-core-graphics-functions.html

另一个提示:NSLog(@"%@", NSStringFromCGPoint(toggle.center))使得CGTypes容易的记录。等效使用:NSStringFromCGRect(rect)

0
if (newLocation.y > NSMaxY(touch.view.frame)) newLocation.y = NSMaxY(touch.view.frame); 
if (newLocation.y < NSMinY(touch.view.frame)) newLocation.y = NSMinY(touch.view.frame); 
toggle.center = newLocation; 

如果您愿意,您可以对x坐标执行相同操作。

+0

即时通讯有点新手。你可以把它放到我的代码中来展示给我看。我不太明白。 – Omar

+0

它恰好在'toggle.center = newLocation;'之前,就像我写的一样。 – jtbandes

+0

有没有使用框架的另一种方式吗? – Omar