ios - 可拖动图像 ios 的边界

标签 ios draggable uitouch boundary

我正在尝试创建一个可拖动的图像,但我试图将其拖动限制在一个小方 block 内而不是整个屏幕内。有人可以告诉我哪里出错了吗?我已将到目前为止的代码放在下面:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    if([touch view] == dot) {
        CGPoint location = [touch locationInView:self.view];
        dot.center = location;
        if (location.x >10) {
            location.x =10;
        } else if (location.x <10) {
            location.x = 10;
        }
        if (location.y >20) {
            location.y =20;
        } else if (location.y < 20) {
            location.y = 20;
        }      
    }
}

最佳答案

您在对其进行更改之前分配位置

首先将限制应用于 location,然后将其分配给 dot

此外,您显示的限制会将您的头寸锁定在 10,20,因为您不允许它超过 10 或小于 10。与 20 一样。

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    if([touch view] == dot) {
        CGPoint location = [touch locationInView:self.view];
        location.x = MIN(MAX(location.x, 0),10);
        location.y = MIN(MAX(location.y, 0),20);
        dot.center = location;     
    }
}

关于ios - 可拖动图像 ios 的边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11052490/

相关文章:

jquery 对话框 : dragging dialog with iframe inside

ios - 将平移手势识别器限制为特定圆圈

ios - 单元测试 Swift- 从 Storyboard 中转换 View Controller 不起作用

ios - 从 Storyboard iOS 导出或打印自动布局约束

ios - 如何正确返回 JSON 短语的函数?

jquery - droppabledraggable在移动时与div重叠

ios - UIPickerView 没有显示任何东西

javascript - 自定义拖放实现

ios - 如何顺利移动 UIImageViews 数组?

ios - 使用 SpriteKit 触摸屏幕时不会返回正确的信息