使用按钮触摸位置 swift 3

Touch location using button swift 3

我有一个大按钮,当用户点击时我想找到他们手指的位置。我熟悉使用 TouchesBegan 方法中的 UITouches 查找点击位置。有什么方法可以从 UIButton 获取位置吗?

我的代码:

 @IBAction func buttonPressed(_ sender: UIButton) {

    //Find touch location here

}

您需要子类化 UIButton 并使用 touchesBegan 您可以获得相对于 Button 本身或相对于 superview 的触摸位置

   class TouchReporterButton: UIButton {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        let touch = touches.first

        let location = touch?.location(in: self.superview);
        if(location != nil)
        {
            //Do what you need with the location
        }
    }

}

希望对您有所帮助