2013-02-07 37 views
1

我試圖創建一個控制,其中用戶可以觸摸和框架內移動的按鈕的矩形框架內移動的按鈕(左/右)。這是我的代碼。像開關

- (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event 
{ 

    UITouch *touch = [[event touchesForView:button] anyObject]; 

    // get delta 
    CGPoint previousLocation = [touch previousLocationInView:button]; 
    CGPoint location = [touch locationInView:button]; 
    CGFloat delta_x = location.x - previousLocation.x; 
    CGFloat delta_y = location.y - previousLocation.y; 

    // move button 
    button.center = CGPointMake(button.center.x + delta_x, 
           button.center.y + delta_y); 


} 

我能夠移動的按鈕(通過觸摸並拖動),但如何限制按鈕,這樣它可以在矩形框內僅右左/移動。

回答

2

也許這個方法會幫助你。我在一段時間前的簡單乒乓遊戲中使用了它。 UIView是乒乓球遊戲的反彈墊。我已經將反彈墊的移動限制在x方向而不是屏幕邊界之外。

如果事情是不明確寫評論,我會盡力解釋。

// Method for movement of the bouncing pad. Restricted movement to x-axis inside of bounds. 
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 

    UITouch *aTouch = [touches anyObject]; 
    CGPoint loc = [aTouch locationInView:self]; 
    CGPoint prevloc = [aTouch previousLocationInView:self]; 

    CGRect myFrame = self.frame; 

    // Checking how far we have moved from the previous location 
    float deltaX = loc.x - prevloc.x; 

    // Note that we only update the x-position of the pad to prevent it from moving in the y-direction. 
    myFrame.origin.x += deltaX; 

    // Making sure that the bouncePad cannot move outside of the screen 
    if(myFrame.origin.x < 0){ 
     myFrame.origin.x = 0; 
    } else if (myFrame.origin.x + myFrame.size.width > [UIScreen main Screen].bounds.size.width) { 
     myFrame.origin.x = [UIScreen mainScreen].bounds.size.width - myFrame.size.width; 
    } 

    // Setting the bouncing pad frame to the one with the updated position from the touches moved event. 
    [self setFrame:myFrame]; 

} 
+0

謝謝,我想用這段代碼。 – user1787741

+0

+1會讓我高興,如果這有助於你! :) – Groot

0

無論是硬編碼的座標極端或視圖內使(UR rectange),並使用剪輯的邊界爲您的按鈕

1

您應該只改變X沒有Ÿ如果你想向左移動和右只是改變下面的代碼

// move button YOUR CODE 
button.center = CGPointMake(button.center.x + delta_x, 
          button.center.y + delta_y); 

// move button REMOVED + delta_y 
button.center = CGPointMake(button.center.x + delta_x, 
          button.center.y); 
+0

謝謝,我這樣做,但我應該如何限制框架。 – user1787741

+0

你可以把一個檢查像float x = button.center.x + delta_x;如果(x> 10 || x <200){button.center = CGPointMake(x,button.center.y);}或者,使用你的frame x和width + x – iphonic