我正在尝试创建一个控件,用户可以在其中触摸和移动框架内的按钮。这是我的代码。
- (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);
}
我可以移动按钮(通过触摸和拖动),但如何限制按钮,使其只能在矩形框架内向左/向右移动。
发布于 2013-02-07 09:38:11
也许这个方法会对你有所帮助。我在不久前制作的一个简单的乒乓球游戏中使用了它。它适用于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-07 09:51:04
您应该只更改X而不是Y,如果您想左右移动,只需更改代码,如下所示
// 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-07 09:46:03
或者对极端坐标进行硬编码,或者在视图(您的矩形)内进行编码,并使用剪辑来限定按钮的边界
https://stackoverflow.com/questions/14747699
复制相似问题