编辑代码

//5.1.2触摸事件
//
//ViewController.swift
//GraphDemo
//
//Created by Zhifeng Chen  on  2020/8/4.
//
import UIKit
class CoreGraphUIView : Uivew {
    override func touchesBegan(_touches: Set<UITouch>,with event: UIEvent?){
        self.backgroundColor = UIColor.red
        print("Began:\(touches)")
    }
    override func touchesEeded(_touches: Set<UITouch>,with event: UIEvent?){
        self.backgroundColor = UIColor.lightGray
        print("Ended:\(touches)")
    }
    override func touchesMoved(_touches: Set<UITouch>,with event: UIEvent?){
        self.backgroundColor = UIColor.blue
        print("Moved:\(touches)")
    }
}
class ViewController: UIViewController{
    override func viewDidload() {
        super.viewDidload()
        //Do any additional setup after loading the view.
        let height = self.view.frame.size.height
        let width = self.view.frame.size.width
        let graphFrame = CGRect(x: 0,y: 0,width: width,height:height)
        let graphview = CoreGraphUIView(frame: graphFrame)
        graphView.backgroundColor = UIColor.white
        self.view.addSubview(graphview)
    }
}
//如果想获得触摸的对象及其坐标,程序如下:
let touch:UITouch = touches.first! as UITouch
print(touch.location(in: view).x)
print(touch.location(in: view).y)