gpt4 book ai didi

ios - 在矩形框(如开关)内移动按钮(向左/向右)

转载 作者:行者123 更新时间:2023-12-01 19:13:37 28 4
gpt4 key购买 nike

我正在尝试创建一个控件,用户可以在该控件中触摸并移动框架内的按钮。这是我的代码。

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


}

我能够移动按钮(通过触摸和拖动),但是如何限制按钮,以便它只能在矩形框架内向左/向右移动。

最佳答案

也许这种方法会帮助您。我在不久前制作的一个简单的Pong游戏中使用了它。它是用于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];

}

关于ios - 在矩形框(如开关)内移动按钮(向左/向右),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14747699/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com