2011-07-03 33 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