Swift 如何實現手勢識別

jopen 10年前發布 | 19K 次閱讀 Swift Apple Swift開發

在這次IOS應用開發教程中,我們打算實現手勢識別。正如你所知道的,IOS支持大量的手勢操作,它們能提供了很好的應用控制和出色用戶體驗。

讓我們開始吧!

首先需要在Xcode中創建一個新的Single View Application:

Swift 如何實現手勢識別

然后點擊Next,彈出的窗口要求你填寫項目設置。在第一欄 (“Product name”) 中填入項目名稱后,點擊Next.

確保語言選擇的是 “Swift”.

Swift 如何實現手勢識別

設計界面

點擊 “Main.storyboard” 文件,拖出6個 UIViews放到視圖中.把視圖排列成如圖所示的樣子.當你排列UIViews時,在每個view下面添加一個UILabel并依圖設定文本值。

Swift 如何實現手勢識別

我們開始寫代碼吧.

是時候編輯實現文件了 (在我們的案例 “ViewController.swift” ).

為了聲明一些我們將會用到的變量,要在 “class ViewController: UIViewController “塊中添加如下代碼.

class ViewController: UIViewController {
    @IBOutlet var tapView: UIView
    @IBOutlet var swipeView: UIView
    @IBOutlet var longPressView: UIView
    @IBOutlet var pinchView: UIView
    @IBOutlet var rotateView: UIView
    @IBOutlet var panView: UIView
    var lastRotation = CGFloat()
    let tapRec = UITapGestureRecognizer()
    let pinchRec = UIPinchGestureRecognizer()
    let swipeRec = UISwipeGestureRecognizer()
    let longPressRec = UILongPressGestureRecognizer()
    let rotateRec = UIRotationGestureRecognizer()
    let panRec = UIPanGestureRecognizer()
}

在第2 – 7行,我們聲明了在之前界面里排列過的 UIViews.

在第8行,我們聲明了實現旋轉手勢要用到的變量(lastRotation).

在第 9 – 14行,我們為每個view聲明了一個手勢識別對象.

注意: 在 Swift中,我們用let關鍵字聲明常量,這意味著它的值在程序運行時不可改變。關鍵字var則聲明普通變量。

當聲明完應用需要的主要變量后,在viewDidLoad 方法中添加如下代碼.

override func viewDidLoad() {
    super.viewDidLoad()
    tapRec.addTarget(self, action: "tappedView")
    pinchRec.addTarget(self, action: "pinchedView:")
    swipeRec.addTarget(self, action: "swipedView")
    longPressRec.addTarget(self, action: "longPressedView")
    rotateRec.addTarget(self, action: "rotatedView:")
    panRec.addTarget(self, action: "draggedView:")
    tapView.addGestureRecognizer(tapRec)
    swipeView.addGestureRecognizer(swipeRec)
    pinchView.addGestureRecognizer(pinchRec)
    longPressView.addGestureRecognizer(longPressRec)
    rotateView.addGestureRecognizer(rotateRec)
    panView.addGestureRecognizer(panRec)
    rotateView.userInteractionEnabled = true
    rotateView.multipleTouchEnabled = true
    pinchView.userInteractionEnabled = true
    pinchView.multipleTouchEnabled = true
    tapView.userInteractionEnabled = true
    swipeView.userInteractionEnabled = true
    longPressView.userInteractionEnabled = true
    panView.userInteractionEnabled = true
}

第 3 – 8行,為每個視圖設定手勢識別的目標。所謂的目標,就是每個view中的手勢完成后要調用的方法。

第 9 -14行,把手勢識別添加到視圖中.

第15 – 22行,把每個視圖的 userInteractionEnabled 屬性設為ture,并把擁有需要多點觸控(rotateView and pinchView)的手勢所在的視圖的multipleTouchEnabled 屬性設為true.

現在,我們編寫每個手勢識別器要調用的方法 (第3 – 8行設置的目標方法 ).

添加如下代碼:

func tappedView(){
    let tapAlert = UIAlertController(title: "Tapped", message: "You just tapped the tap view", preferredStyle: UIAlertControllerStyle.Alert)
    tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
    self.presentViewController(tapAlert, animated: true, completion: nil)
}
 
func swipedView(){
    let tapAlert = UIAlertController(title: "Swiped", message: "You just swiped the swipe view", preferredStyle: UIAlertControllerStyle.Alert)
    tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
    self.presentViewController(tapAlert, animated: true, completion: nil)
}
 
func longPressedView(){
    let tapAlert = UIAlertController(title: "Long Pressed", message: "You just long pressed the long press view", preferredStyle: UIAlertControllerStyle.Alert)
    tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
    self.presentViewController(tapAlert, animated: true, completion: nil)
}

這三種方法都很好地完成同一件事.每次在手勢在相應的視圖中完成后,每種方法都彈出一個對話框.

所以 tappedView() 方法在用戶滑動視圖時彈出一個對話框,swipedView() 方法在用戶觸摸滑動 swipe視圖時彈出對話框,而longPressedView() 方法則在用戶長按long press view時彈出對話框.

另兩種手勢 (rotate and pinch ) 的代碼稍微有點復雜.

為旋轉手勢添加如下代碼:

func rotatedView(sender:UIRotationGestureRecognizer){
    var lastRotation = CGFloat()
    self.view.bringSubviewToFront(rotateView)
    if(sender.state == UIGestureRecognizerState.Ended){
    lastRotation = 0.0;
    }
    rotation = 0.0 - (lastRotation - sender.rotation)
    var point = rotateRec.locationInView(rotateView)
    var currentTrans = sender.view.transform
    var newTrans = CGAffineTransformRotate(currentTrans, rotation)
    sender.view.transform = newTrans
    lastRotation = sender.rotation
}

這個方法包含 sender:UIRotationGestureRecognizer 參數. sender 參數( UIRotationGestureRecognizer 類型) 含有這個方法(在這個案例中是rotateRec)調用的手勢識別器的值.

第2行聲明了 lastRotation.

第3行我們把 rotateView放到前面.

接下來,在 if語句中,我們檢查手勢是否完成,如果沒有完成,我們就將視圖旋轉。

第 8 – 10行,我們計算rotate view的旋轉程度,第10行,我們設置rotate view的旋轉程度。

On line 12 we set the lastRotation 作為旋轉手勢識別器的當前旋轉.

現在我們添加pinch 手勢的代碼:

func pinchedView(sender:UIPinchGestureRecognizer){
    self.view.bringSubviewToFront(pinchView)
    sender.view.transform = CGAffineTransformScale(sender.view.transform, sender.scale, sender.scale)
    sender.scale = 1.0
}

在之前方法的第1行中,我們把pinch視圖放到了頂端。然后設置每個pinch視圖的transform,并把pinchRec的scale設為1.

然后是實現 pan (drag) 手勢. 添加如下代碼:

func draggedView(sender:UIPanGestureRecognizer){
    self.view.bringSubviewToFront(sender.view)
    var translation = sender.translationInView(self.view)
    sender.view.center = CGPointMake(sender.view.center.x + translation.x, sender.view.center.y + translation.y)
    sender.setTranslation(CGPointZero, inView: self.view)
}

第2行,我們把 drag視圖放到頂端 (和前面的方法一樣).

然后我們聲明變量translation,并用 sender.translationInView(self.view)的值給它賦值。 完成后,把sender.view object (panRec) 的center屬性設為計算出來的新center  ( 通過CGPointMake(sender.view.center.x + translation.x, sender.view.center.y + translation.y) 計算) 并把translation 設為 sender (panRec).

現在,代碼部分算是完成了!

回到界面設計.

現在我們回到 “Main.storyboard” 文件. 選擇視圖控制器并把聲明的每個UIView連接到相應的視圖,如下圖所示.

Swift 如何實現手勢識別

 

完工

現在你可以在模擬器或你的設備上運行該應用并測試手勢。

后記

我希望這篇教程對你有所幫助。你可以在下載完整源代碼,另外如果有什么問題,可以通過 推ter 聯系我.

最后,請在psdapps.gr上試用我的IOS應用.

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!