iOS UIButton 按钮触摸拖动进入功能无法正常工作?

5
我正在尝试创建一个按钮,在用户的触摸被带到按钮的任何位置时都会触发操作(无论他们在内部按下,还是从外部拖到内部)。本质上,我需要创建一种方式,只要手指在按钮内部,就可以触发操作。
“Touch drag enter”结合“touch down inside”似乎可以完成任务,但它似乎与我所需的不同。
另外,我更喜欢在storyboard中完成,而不是硬编码(如touchesBegan / moved),但如果没有其他方法,那也可以。
4个回答

5

Touch drag enter 只有在您在控件内开始触摸并将其拖到控件边界之外,然后再次拖回控件内而不离开触摸时才会被调用。因此,您需要子类化您的按钮并实现所需功能。


3

你可以选择逐个绑定所有事件,并在IB中按下按钮时调用你想要的方法。

或者

你可以尝试在代码中注册你的按钮到UIControlEventAllTouchEvents。这是一个有用的示例:

[_btnRoundRect addTarget:self action:@selector(btnPressedAction) forControlEvents:UIControlEventAllTouchEvents];


- (void)btnPressedAction{
    NSLog(@"Bttn pressed");
}

0

刚刚遇到了这个问题,虽然我看到这个问题很旧了,但我猜可能还有人也会遇到...

我的解决方案是使用touchesBegan、touchesMoved、touchesEnded和touchesCancelled。

我禁用了我的按钮,尽管你可以把它们转换成UIView... 然后在touchesBegan中,我对所有触摸事件使用.point(inside:)并检查所有按钮,调用被触摸的那些按钮上的buttonDown函数。

然后在touchesMoved中,我再次检查,但同时使用当前触摸位置和上一个触摸位置来查看该触摸是否进入了新按钮。基本上,如果上一个按钮被触摸而不是新的按钮,我就为该按钮调用buttonUp函数。如果情况相反,我就调用buttonDown函数。

最后,在touchesEnded和touchesCancelled中,我只看一下正在被点击的按钮,然后调用buttonUp函数。

我已经在实际设备上和Mac Catalyst上进行了多点触控测试,似乎都能正常工作。这是一个快速解决方案,不需要改变我之前使用的常规“带有目标/操作”的按钮解决方案...

示例:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            for b in keys {
                if b.point(inside: touch.location(in: b),with:nil) {
                    keyDown(b)
                }
            }
        }
    }

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            for b in keys {
                if b.point(inside: touch.location(in: b),with:nil) && !b.point(inside: touch.previousLocation(in: b), with:nil) {
                    keyDown(b)
                } else if b.point(inside: touch.previousLocation(in: b), with:nil) && !b.point(inside: touch.location(in: b),with:nil) {
                    keyUp(b)
                }
                
            }
        }
    }
    
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            for b in keys {
                if b.point(inside: touch.location(in: b),with:nil) {
                    keyUp(b)
                }
            }
        }
    }
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            for b in keys {
                if b.point(inside: touch.location(in: b),with:nil) {
                    keyUp(b)
                }
            }
        }
    }

0

当在IB中设置连接时,应该寻找Touch Down。每当用户的手指触碰按钮时,动作将被调用。


2
这并不解决 OP 的需求,即在触碰按钮时触发操作的问题。 - Ben Wheeler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接