Swift 通过touchesBegan 方法获取用户点击的view,模拟连续点击效果

 

 

一:代码实现

   var mV:UIView!
  var flag = false

    override func viewDidLoad() {

        super.viewDidLoad()

        mV = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100 ))

        mV.backgroundColor = UIColor.red

        self.view.addSubview(mV)

    }

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

        for touch:AnyObject in touches{

//            方法一

//            //获取用户点击的坐标

//            var point = (touch as AnyObject).location(in: self.view)

//            //将用户点击的点坐标,从self.view.layer转换到mV.View.layer的点坐标

//            point = self.mV.layer.convert(point, from: self.view.layer)

//            print("point\(point)")

//            let point2 = self.mV.layer.convert(point, to: self.view.layer)

//            print("point2\(point2)")

//

//            if self.mV.layer.contains(point ){

//                print(1)

//            }

            
            //方法二

            //获取用户点击的坐标

            var point = (touch as AnyObject).location(in: self.view)

            //返回在图层层次中包含point的view.layer的最远子代,即获取到用户点击的View的layer

            let layer = view.layer.hitTest(point)

            if layer == mV.layer{

                //模拟连续点击效果

                let t:UITouch = touch  as! UITouch

                let i = t.tapCount

                if t.tapCount >= 2{

                    flag = true

                }
                if flag{
                    print(i)
                }
            }
        }
        flag = false
    }

 

二:效果显示

 

posted @ 2018-05-29 21:22  小炮陈  阅读(3704)  评论(0编辑  收藏  举报