1. 程式人生 > >Swift基礎--手勢識別(雙擊、捏、旋轉、拖動、划動、長按)

Swift基礎--手勢識別(雙擊、捏、旋轉、拖動、划動、長按)

//
//  ViewController.swift
//  JieUITapGestureRecognizer
//
//  Created by jiezhang on 14-10-4.
//  Copyright (c) 2014年 jiezhang. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UIActionSheetDelegate {
    
    @IBOutlet var im: UIImageView!
    var lastScaleFactor : CGFloat! = 1  //放大、縮小
    var netRotation : CGFloat = 1;//旋轉
    var netTranslation : CGPoint!//平移
    var images : NSArray = ["meinv1.jpg","mv2.jpg","mv3.jpg","mv4.jpg","mv5.jpg","mv6.jpg"]// 圖片陣列
    var imageIndex : Int = 0 //陣列下標

    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        netTranslation = CGPoint(x: 0, y: 0)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
      
        
        var tapGesture = UITapGestureRecognizer(target: self, action: "handleTapGesture:")
        //設定手勢點選數,雙擊:點2下
        tapGesture.numberOfTapsRequired = 2
        self.view.addGestureRecognizer(tapGesture)
        
        //手勢為捏的姿勢:按住option按鈕配合滑鼠來做這個動作在虛擬器上
        var pinchGesture = UIPinchGestureRecognizer(target: self, action: "handlePinchGesture:")
        self.view.addGestureRecognizer(pinchGesture)
        
        //旋轉手勢:按住option按鈕配合滑鼠來做這個動作在虛擬器上
        var rotateGesture = UIRotationGestureRecognizer(target: self, action: "handleRotateGesture:")
        self.view.addGestureRecognizer(rotateGesture)
        
        //拖手勢
        var panGesture = UIPanGestureRecognizer(target: self, action: "handlePanGesture:")
//        self.view.addGestureRecognizer(panGesture)
        
        //划動手勢
        //右劃
        var swipeGesture = UISwipeGestureRecognizer(target: self, action: "handleSwipeGesture:")
        self.view.addGestureRecognizer(swipeGesture)
        //左劃
        var swipeLeftGesture = UISwipeGestureRecognizer(target: self, action: "handleSwipeGesture:")
        swipeLeftGesture.direction = UISwipeGestureRecognizerDirection.Left //不設定是右
        self.view.addGestureRecognizer(swipeLeftGesture)
        
        //長按手勢
        var longpressGesutre = UILongPressGestureRecognizer(target: self, action: "handleLongpressGesture:")
        //長按時間為1秒
        longpressGesutre.minimumPressDuration = 1
        //允許15秒運動
        longpressGesutre.allowableMovement = 15
        //所需觸控1次
        longpressGesutre.numberOfTouchesRequired = 1
        self.view.addGestureRecognizer(longpressGesutre)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //雙擊螢幕時會呼叫此方法,放大和縮小圖片
    func handleTapGesture(sender: UITapGestureRecognizer){
        //判斷imageView的內容模式是否是UIViewContentModeScaleAspectFit,該模式是原比例,按照圖片原時比例顯示大小 
        if im.contentMode == UIViewContentMode.ScaleAspectFit{
            //把imageView模式改成UIViewContentModeCenter,按照圖片原先的大小顯示中心的一部分在imageView
           im.contentMode = UIViewContentMode.Center
        }else{
            im.contentMode = UIViewContentMode.ScaleAspectFit
        }
    }
    
    //捏的手勢,使圖片放大和縮小,捏的動作是一個連續的動作
    func handlePinchGesture(sender: UIPinchGestureRecognizer){
        var factor = sender.scale
        if factor > 1{
            //圖片放大
            im.transform = CGAffineTransformMakeScale(lastScaleFactor+factor-1, lastScaleFactor+factor-1)
        }else{
            //縮小
            im.transform = CGAffineTransformMakeScale(lastScaleFactor*factor, lastScaleFactor*factor)
        }
        //狀態是否結束,如果結束儲存資料
        if sender.state == UIGestureRecognizerState.Ended{
            if factor > 1{
                lastScaleFactor = lastScaleFactor + factor - 1
            }else{
                lastScaleFactor = lastScaleFactor * factor
            }
        }
    }
    
    //旋轉手勢
    func handleRotateGesture(sender: UIRotationGestureRecognizer){
        //浮點型別,得到sender的旋轉度數 
        var rotation : CGFloat = sender.rotation
        //旋轉角度CGAffineTransformMakeRotation,改變影象角度
        im.transform = CGAffineTransformMakeRotation(rotation+netRotation)
        //狀態結束,儲存資料
        if sender.state == UIGestureRecognizerState.Ended{
            netRotation += rotation
        }
    }
    //拖手勢
    func handlePanGesture(sender: UIPanGestureRecognizer){
        //得到拖的過程中的xy座標
        var translation : CGPoint = sender.translationInView(im)
        //平移圖片CGAffineTransformMakeTranslation
        im.transform = CGAffineTransformMakeTranslation(netTranslation.x+translation.x, netTranslation.y+translation.y)
        if sender.state == UIGestureRecognizerState.Ended{
            netTranslation.x += translation.x
            netTranslation.y += translation.y
        }
    }
    //划動手勢
    func handleSwipeGesture(sender: UISwipeGestureRecognizer){
        //划動的方向
        var direction = sender.direction
        //判斷是上下左右
        switch (direction){
        case UISwipeGestureRecognizerDirection.Left:
            println("Left")
            imageIndex++;//下標++
            break
        case UISwipeGestureRecognizerDirection.Right:
            println("Right")
            imageIndex--;//下標--
            break
        case UISwipeGestureRecognizerDirection.Up:
            println("Up")
            break
        case UISwipeGestureRecognizerDirection.Down:
            println("Down")
            break
        default:
            break;
        }
        //得到不越界不<0的下標
        imageIndex = imageIndex < 0 ? images.count-1:imageIndex%images.count
        //imageView顯示圖片
        im.image = UIImage(named: images[imageIndex] as String)
    }
    
    //長按手勢
    func handleLongpressGesture(sender : UILongPressGestureRecognizer){
        
        if sender.state == UIGestureRecognizerState.Began{
            //建立警告
            var actionSheet = UIActionSheet(title: "Image options", delegate: self, cancelButtonTitle: "cancel", destructiveButtonTitle: "ok", otherButtonTitles: "other")
            actionSheet.showInView(self.view)
        }
    }
}

注意:滑動手勢和拖手勢衝突,兩個選一個測試,至於測試的效果自己新建一個工程來把程式碼加入就行