如何从touchesBegan事件中获取CGPoint?

时间:2016-01-13 22:58:16

标签: ios swift

在我的AppDelegate中,我想检测何时对状态栏进行了点击事件。为了做到这一点,我需要从事件中获取CGPoint。我如何从这段代码中获取它?

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    super.touchesBegan(touches, withEvent: event)

    let location = // how to get a CGPoint ????

    let statusBarFrame = UIApplication.sharedApplication().statusBarFrame
    if CGRectContainsPoint(statusBarFrame, location){
        print("Status bar touched")
    }else{
        print("Not touched")
    }

}

4 个答案:

答案 0 :(得分:1)

你正在使用Swift 2;您可以按如下方式检索点击位置:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)
{
    if let touch = touches.first as? UITouch
    {
        //The view you would like to get the tap location from.
        let tapPoint = touch.locationInView(self.view) 
        let statusBarFrame = UIApplication.sharedApplication().statusBarFrame
        if CGRectContainsPoint(statusBarFrame, tapPoint)
        {
            print("Status bar touched")
        }
        else
        {
            print("Not touched")
        }
    }
}

答案 1 :(得分:1)

UITouch对象的方法locationInView:允许您在特定视图中查找触摸的位置。来自文档:

  

返回给定视图坐标系中接收器的当前位置。

     

您希望触摸位于其坐标系中的视图对象。处理触摸的自定义视图可以指定self以在其自己的坐标系中获得触摸位置。 传递nil以获取窗口坐标中的触摸位置。

所以试试:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    super.touchesBegan(touches, withEvent: event)

    guard let touch = touches.first else {
        return
    }

    let location = touch.locationInView(nil)

    let statusBarFrame = UIApplication.sharedApplication().statusBarFrame
    if CGRectContainsPoint(statusBarFrame, location) {
        print("Status bar touched")
    } else {
        print("Not touched")
    }
}

无论设备方向如何,都可以使用

答案 2 :(得分:0)

你必须有一个你触摸的视图。如果您设法让您的应用委托接收触摸事件,您可以尝试获取locationInView:使用app delegates窗口。

答案 3 :(得分:0)

Swift 5.1

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {


    super.touchesBegan(touches, with: event)

    guard let touch = touches.first else {
        return
    }

    let location = touch.location(in: nil)

}