触摸事件初步使用

//
//  ViewController.swift
//  触摸事件
//
//  Created by admin on 16/1/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    // 触摸开始
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        // 获取touch对象
        let touch = (touches as NSSet).anyObject()
        // 获取当前点击的位置,位置坐标是相对于当前传入的view,如果传入nil就是想对于整个窗口
        print(touch!.locationInView(touch!.view))
        // 获取连续点击的次数
        print(touch!.tapCount)
    }
    // 触摸移动
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()
        print("移动前的坐标\(touch?.previousLocationInView(touch?.view))")
        print("移动后的坐标\(touch?.locationInView(touch?.view))")
        print("==============")
        // 拖动view的时候改变view的位置
        let point = ((touch?.view)! as UIView).center
        ((touch?.view)! as UIView).center = CGPointMake(point.x + ((touch?.locationInView(touch?.view).x)! - (touch?.previousLocationInView(touch?.view).x)!), point.y + ((touch?.locationInView(touch?.view).y)! - (touch?.previousLocationInView(touch?.view).y)!))
    }
    // 触摸结束
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {

    }
    // 终止触摸,譬如被打电话提前结束
    override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {

    }
    override func touchesEstimatedPropertiesUpdated(touches: Set<NSObject>) {

    }
}

标签: swift, 触摸事件

添加新评论