我正在尝试创建一个控件,用户可以触摸并移动框架内的按钮。这是我的代码。
- (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);
}
我可以移动按钮(通过触摸和拖动),但是如何限制按钮,以便它只能在矩形框内向左/向右移动。
答案 0 :(得分: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];
}
答案 1 :(得分:1)
如果您想左右移动,只应更改 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);
答案 2 :(得分:0)
要么对极值的坐标进行硬编码,要么在视图(矩形)内进行硬编码,并使用剪辑来界定按钮