2011-08-04 38 views
0

我不是要求givemesamplecodenow響應,只是在正確的方向微調將不勝感激。我的搜索沒有任何好處。拖放UIButton但限制到邊界

我有一個UIButton,我可以在屏幕上自由移動。

我想限制這個對象的拖動區域,所以它只能上下或左右移動。我相信我需要獲得邊界的x,y座標,然後限制在該區域之外的移動。但是,這是我得到的。我的知識並沒有比這更進一步。

有沒有人在過去實現過類似的東西?

亞當

回答

4

所以我們可以說你在拖拽操作的中間是。通過將其中心設置爲引起運動的任何手勢的中心,您都可以移動按鈕實例。

如果您不喜歡,可以通過測試手勢中心和重置中心值來施加限制。下面假定一個按鈕連接到所有觸摸拖動事件的動作,但如果使用手勢識別器或touchesBegan:和朋友,則該原則仍然適用。

- (IBAction)handleDrag:(UIButton *)sender forEvent:(UIEvent *)event 
{ 
    CGPoint point = [[[event allTouches] anyObject] locationInView:self.view]; 

    if (point.y > 200) 
    { 
     point.y = 200; //No dragging this button lower than 200px from the origin! 
    } 

    sender.center = point; 
} 

如果你想要一個按鈕,滑動只在一個方向,那是很容易:

- (IBAction)handleDrag:(UIButton *)sender forEvent:(UIEvent *)event 
{ 
    CGPoint point = [[[event allTouches] anyObject] locationInView:self.view]; 
    point.y = sender.center.y; //Always stick to the same y value 

    sender.center = point; 
} 

或者你想要的按鈕拖動只有特定視圖的區域內。如果你的界限很複雜,這可能會更容易定義。

- (IBAction)handleDrag:(UIButton *)sender forEvent:(UIEvent *)event 
{ 
    CGPoint point = [[[event allTouches] anyObject] locationInView:self.someView]; 

    if ([self.someView pointInside:point withEvent:nil]) 
    { 
     sender.center = point; 
     //Only if the gesture center is inside the specified view will the button be moved 
    } 
} 
+0

絕對的輝煌,工作過一種享受。 –

1

想必你會使用touchesBegan:touchesMoved:等,所以應儘可能測試,簡單觸摸點是否是你的看法在touchesMoved:邊界之外。如果在外面,請忽略它,但如果它在裏面,請調整按鈕的位置。

我懷疑你會發現這個功能很有用:

bool CGRectContainsPoint (CGRect rect, CGPoint point);