IOS swift多点触控

本文介绍如何使用Swift在iOS应用中实现多点触控功能,特别是在视图上通过两个手指的平移来控制图片的放大和缩小。通过覆盖`touchesBegan`、`touchesMoved`和`touchesEnded`方法,监测并处理触控事件,实现图片的动态缩放效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 override func viewDidLoad() {
        super.viewDidLoad()
        self.view.multipleTouchEnabled=true//是否开启多点触摸
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        //获得焦点的坐标
//        var l:CGPoint=((touches as NSSet).anyObject())!.locationInView(self.view) as CGPoint
//        println("x:\(l.x),y:\(l.y)")
//        println("touchesBegan按下")
    }
    override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
       // println("touchesEnded抬起")
    }
    private var lastDistance:CGFloat = 0.0
    override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
//        println(touches.count)
//        //获得每个焦点
//        for touche in touches{
//            //获得焦点的坐标
//            var l:CGPoint = (touche as AnyObject).locationInView(self.view) as CGPoint
//            println("x:\(l.x),y:\(l.y)")
//        }
//        
//        println("touchesMoved移动")
        
        if touches.count == 2 {
            var p1:CGPoint=(touches as NSSet).allObjects[0].locationInView(self.view) as CGPoint
            var p2:CGPoint=(touches as NSSet).allObjects[1].locationInView(self.view) as CGPoint
            var xx = p1.x - p2.x
            var yy = p1.y - p2.y
            var currenDistance:CGFloat=sqrt(xx*xx+yy*yy)
            if lastDistance == 0.0{
                lastDistance = currenDistance
            }else{
                if lastDistance-currenDistance > 3{
                    println("缩小")
                    image.transform=CGAffineTransformScale(image.transform, 0.9, 0.9)
                }else if lastDistance-currenDistance <  -3{
                    println("放大")
                    image.transform=CGAffineTransformScale(image.transform, 1.1, 1.1)
                }
                lastDistance = currenDistance
            }
        }
        
    }
    override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
       // println("touchesCancelled")
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值