【问题标题】:Triggering a UIButton's method when user drags finger into button's area?当用户将手指拖入按钮区域时触发 UIButton 的方法?
【发布时间】:2013-06-09 07:07:22
【问题描述】:

我想要一个在以下条件下触发其方法的按钮:

  • 当用户点击按钮时
  • 当用户按下按钮并将他/她的手指拖出按钮区域时
  • 当用户将手指从按钮区域外拖到按钮区域内时

基本上,无论何时触摸按钮的任何部分,无论触摸的来源如何,我都希望触发该方法,但希望通过操作 UIButton 属性来完成此操作,例如touchedUpInside 等。

感谢您的建议!

【问题讨论】:

  • 您需要将UIGestureRecognizer 添加到您的UIButton。向我们展示您迄今为止的尝试?
  • 我尝试过使用 UIGestureRecognizers。我不喜欢他们的回应,因为我不想检测滑动等。即使用户只将手指从按钮外侧移动到按钮内侧 5 个像素,我也希望检测到这一点。
  • 尝试查看视图的 hittest 方法,您可以操作其中的所有触摸事件
  • 你能发布一些示例代码吗?我不明白如何为此目的实施 hitTest
  • 只有当触摸从按钮外部拖到内部时才需要触发事件,反之亦然?还是应该在触摸按钮后立即启动(可以从外移到内或从内移到外)?

标签: ios objective-c xcode uibutton


【解决方案1】:

关于:

  • 当用户按下按钮并将他/她的手指拖出按钮区域时

我最近做了类似的事情。这是我在 Swift 中的代码。

(在此示例中,您将 UIButton 子类化,例如:class FadingButton: UIButton

...

// The user tapped the button and then moved the finger around.
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesMoved(touches, with: event)

    // Get the point to which the finger moved
    if let point: CGPoint = touches.first?.location(in: self) {

        // If the finger was dragged outside of the button...
        if ((point.x < 0 || point.x > bounds.width) ||
            (point.y < 0 || point.y > bounds.height)) {

            // Do whatever you need here
        }
    }
}
...

我希望它对某人有所帮助。

【讨论】:

    【解决方案2】:

    您需要将以下 UIControlEvents 添加到您的按钮:

    1. UIControlEventTouchUpInside
    2. UIControlEventTouchDragOutside
    3. UIControlEventTouchDragInside

    这样

        [self.myButton addTarget:self action:@selector(dragMoving:withEvent: )
                  forControlEvents: UIControlEventTouchDragInside | UIControlEventTouchDragOutside];
    
        [self.myButton addTarget:self action:@selector(dragEnded:withEvent: )
                  forControlEvents: UIControlEventTouchUpInside |
         UIControlEventTouchUpOutside];
    
        [self.myButton addTarget:self action:@selector(myButtonTouchDown:withEvent: )
                  forControlEvents: UIControlEventTouchDown];
    

    【讨论】:

      【解决方案3】:

      让你的方法如-(IBAction)btnTap 并连接到这些属性

      • 当用户点击按钮时。 - 为此使用Touch Down 方法
      • 当用户按下按钮并将他/她的手指拖出 按钮区域 - 为此目的使用 Touch Up Inside
      • 当用户将他/她的手指从按钮区域外拖动到 在按钮内部 - Touch Drag Inside

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-03
        • 2016-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-26
        • 2017-02-11
        • 2011-09-18
        • 1970-01-01
        相关资源
        最近更新 更多