【问题标题】:set up UITouch's moving range设置 UITouch 的移动范围
【发布时间】:2016-02-26 00:03:27
【问题描述】:

我为大小为 (30, 50) 的标签创建了一个触摸移动事件。这是代码

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {    
    UITouch *touch = [touches anyObject];
    UIView *superView = self.superview;
}

但我需要确保标签只能在超级视图内移动。也就是说UILabel在“接触”到view的边缘时会停止移动,如何设置label的移动范围?

【问题讨论】:

  • 您要将标签移动到触摸的位置吗?
  • 到目前为止您尝试过什么?您可以将其添加到您的问题中吗?我认为您可能必须处理 touchesMoved 方法中的移动。
  • @UlyssesR 我需要的是让 uilabel 在触及其超级视图的边缘时无法移动。

标签: ios objective-c touch-event


【解决方案1】:
  1. 将标签设置为您的触摸位置
  2. 检查label的frame是否在superView里面
  3. 如果在外面,换框架,把userInteractionEnabled设为NO
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.center = [touches.anyObject locationInView:self.superview];

    CGRect bounds = self.superview.bounds;
    CGRect newFrame = self.frame;

    if (newFrame.origin.x < 0) {
        newFrame.origin.x = 0;
        self.userInteractionEnabled = NO;
    }
    if (newFrame.origin.y<0) {
        newFrame.origin.y = 0;
        self.userInteractionEnabled = NO;
    }
    if (newFrame.origin.x + newFrame.size.width > bounds.size.width) {
        newFrame.origin.x = bounds.size.width - newFrame.size.width;
        self.userInteractionEnabled = NO;
    }
    if (newFrame.origin.y + newFrame.size.height > bounds.size.height) {
        newFrame.origin.y = bounds.size.height - newFrame.size.height;
        self.userInteractionEnabled = NO;
    }

    self.frame = newFrame;
}

【讨论】:

  • 感谢您的帮助。我需要的是标签在外面时不能移动。随着您的标签将在移动结束后返回。也就是说,当 label.origin.x 或 y
  • 可以看到UIView的属性userInteractionEnabled> 默认是YES。如果设置为 NO,则忽略用户事件(触摸、按键)并将其从事件队列中删除。因此,当 label.frame 位于其 superView 之外时,您可以将 userInteractionEnabled 设置为 NO。
  • userInteractionEnabled 仍然不起作用。即使 uilabel 在外面,它也不会停止,直到我停止点击它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-02
  • 1970-01-01
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多