刚刚遇到了这个问题,虽然我看到这个问题很旧了,但我猜可能还有人也会遇到...
我的解决方案是使用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)
}
}
}
}