使用按钮swift 3触摸位置

时间:2017-07-19 15:11:38

标签: ios swift uibutton location touch

我有一个大按钮,当用户点击时我想找到他们手指的位置。我熟悉使用TouchesBegan方法中的UITouches查找水龙头的位置。有没有办法从UIButton获取位置?

我的代码:

 @IBAction func buttonPressed(_ sender: UIButton) {

    //Find touch location here

}

1 个答案:

答案 0 :(得分:2)

您需要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
        }
    }

}

希望这有帮助