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);   


}

ボタンを(タッチしてドラッグすることで)移動できますが、ボタンを制限して、長方形の枠内で左右にしか移動できないようにする方法。

4

3 に答える 3

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];

}
于 2013-02-07T09:38:10.540 に答える
1

左右に移動したい場合は、Yではなく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);
于 2013-02-07T09:51:04.353 に答える
0

極値の座標をハードコーディングするか、ビュー(urrectange)内に作成し、クリップを使用してボタンの境界を設定します

于 2013-02-07T09:46:03.130 に答える