突出显示时 UIButton 周围不需要的不可见检测区域

Unwanted Invisible detection area around UIButton when Highlighted

我正在我的 viewDidLoad 中的通用设备应用程序中创建 "yes" 和 "no" UIButton,如下所示:

   let yesUnpressedTexture = UIImage(contentsOfFile:NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent("yesButtonUnpressed.png"))!
    let yesPressedTexture = UIImage(contentsOfFile:NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent("yesButtonPressed.png"))!
    let buttonWidth = yesUnpressedTexture.size.width
    var yesButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
    yesButton.setImage(yesUnpressedTexture, forState: UIControlState.Normal)
    yesButton.setImage(yesPressedTexture, forState: UIControlState.Highlighted)
    yesButton.frame = CGRect(x: device.x/2 - buttonWidth * worldScale - worldScale * 40, y:  device.y/2 - worldScale * 50, width: buttonWidth * worldScale, height: worldScale * 200)
    yesButton.addTarget(self, action: "deleteProgress:", forControlEvents: UIControlEvents.TouchUpInside)
    self.deleteView.addSubview(yesButton)

    let noUnpressedTexture = UIImage(contentsOfFile:NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent("noButtonUnpressed.png"))!
    let noPressedTexture = UIImage(contentsOfFile:NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent("noButtonPressed.png"))!
    var noButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
    noButton.frame = CGRect(x: device.x/2 + worldScale * 40, y:  device.y/2 - worldScale * 50, width: buttonWidth * worldScale, height: worldScale * 200)
    noButton.setImage(noUnpressedTexture, forState: UIControlState.Normal)
    noButton.setImage(noPressedTexture, forState: UIControlState.Highlighted)
    noButton.addTarget(self, action: "cancelDelete:", forControlEvents: UIControlEvents.TouchUpInside)
    self.deleteView.addSubview(noButton)

它们在我的 iPad 上测试时加载和工作正常,但是当我在任何 iPhone 模拟器上测试时会发生一些奇怪的事情。如果将手指从任一按钮上移开以取消触摸,则必须将手指从按钮上移开很多才能这样做。相应的按钮保持突出显示,直到用户手指超出我在照片中显示的突出显示框之外。

有人知道如何解决这个问题吗?

我尝试使用 CGRectMake 设置框架,但没有任何变化。

这实际上是 OS 的一个特性以及触摸事件的工作原理。当您触摸 UIControl(在您的情况下为 UIButton)时,OS 开始跟踪您的触摸和移动,并且您的控件周围有一个预定义的边界矩形。只有当您将手指移出此边界后,触摸才被认为已退出控件 - 这是当控件失去焦点(突出显示)并且还会触发 TouchDragExitTouchDragOutside 事件时。

如果您想改变这一点,您可以通过创建一个 UIButton 子类并覆盖 continueTrackingWithTouch(_:withEvent:) 方法来自定义跟踪行为,这样您就可以根据自己的逻辑结束跟踪。