1. 程式人生 > >swift--觸摸(UITouch)事件(點擊,移動,擡起)

swift--觸摸(UITouch)事件(點擊,移動,擡起)

send nss spa bject rst sse sta location 耗時

觸摸事件:

UITouch:一個手機第一次點擊屏幕,會形成一個UITouch對象,知道離開銷毀。表示觸碰。UITouch對象能表明當前手指觸碰的屏幕位置、狀態,狀態分為開始觸碰、移動、離開。

具體方法介紹如下:

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

通知調用者當有一個或者多個手指觸摸到了視圖或者窗口時觸發次方法,touches是UITouch的集合,通過uito我們可以檢測觸摸事件的屬性,是單擊還是雙擊,還有觸摸的位置等。

2.override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?)

告訴接受者一個或者多個手指在視圖或者窗口上觸發移動事件。默認不允許多點觸摸,如果要接受多點觸摸事件必須將UIVIew屬性置為true。

//支持多點觸摸
self.view.isMultipleTouchEnabled = true

3.override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?)

當一個觸摸事件結束時發出的UITouch實例對象

4.override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?)

通知接受者當系統發出取消事件的時候(如第內存消耗時的警告框)

樣例代碼:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch:AnyObject in touches {
            let t:UITouch = touch as! UITouch
            //當在屏幕上連續拍動兩下時,背景回復為白色
            if t.tapCount == 2
            {
                self.view.backgroundColor 
= UIColor.white }else if t.tapCount == 1 { self.view.backgroundColor = UIColor.blue } } }
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        //獲取點擊的坐標位置
        for touch:AnyObject in touches {
            let t:UITouch = touch as! UITouch
            print(t.location(in: self.view))
        }
    }
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if touches.count == 2
        {
            //獲取觸摸點
            let first = (touches as NSSet).allObjects[0] as! UITouch
            let second = (touches as NSSet).allObjects[1] as! UITouch
            //獲取觸摸點坐標
            let firstPoint = first.location(in: self.view)
            let secondPoint = second.location(in: self.view)
            //計算兩點間的距離
            let deltaX = secondPoint.x - firstPoint.x
            let deltaY = secondPoint.y - firstPoint.y
            let initialDistance = sqrt(deltaX + deltaY * deltaY)
            print("兩點間的距離:\(initialDistance)")
            //計算兩點間的角度
            let height = secondPoint.y - firstPoint.y
            let width = firstPoint.x - secondPoint.x
            let rads = atan(height/width)
            let degrees = 180.0 * Double(rads) / .pi
            print("兩點間角度:\(degrees)")
        }
    }
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("event canceled!")
    }

swift--觸摸(UITouch)事件(點擊,移動,擡起)