首页 > 代码库 > Swift - 点击箭头旋转

Swift - 点击箭头旋转

 

 

let arrowImage = UIImageView(image: UIImage(named: "Machine_arrow")!.imageWithRenderingMode(.AlwaysTemplate))

        let arrowButton = UIButton(frame: CGRectMake(700, 20, arrowImage.bounds.width, arrowImage.bounds.height))

        arrowButton.addSubview(arrowImage)

        arrowButton.addTarget(self, action: #selector(btnClicked(_:event:)), forControlEvents: .TouchUpInside)

 

// 检查用户点击按钮时的位置,并转发事件到对应的accessorytapped事件

    func btnClicked(sender: UIButton, event: AnyObject) {

        let touches = event.allTouches()! as NSSet

        let touch = touches.anyObject() as! UITouch

        let currentTouchPosition = touch.locationInView(selectTable)

        let indexPath: NSIndexPath = selectTable.indexPathForRowAtPoint(currentTouchPosition)!

        

        tableView(selectTable, accessoryButtonTappedForRowWithIndexPath: indexPath)

    }

    

    // 这样,UITableViewaccessoryButtonTappedForRowWithIndexPath方法会被触发,并且获得一个indexPath 参数。通过这个indexPath 参数,我们可以区分到底是众多按钮中的哪一个附件按钮发生了触摸事件:

    func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {

        let idx = indexPath.row

        //在这里加入自己的逻辑

        print(idx)

        // 点击箭头旋转

        rotat()

        // rotateArrow()

    }

    

    // 旋转动画一

    func rotat() {

        //创建旋转动画

        let anim = CABasicAnimation(keyPath: "transform.rotation")

        //旋转角度

        anim.toValue = 1 * M_PI

        //旋转指定角度需要的时间

        anim.duration = 1

        //旋转重复次数

        anim.repeatCount = MAXFLOAT

        //动画执行完后不移除

        anim.removedOnCompletion = true

        //将动画添加到视图的laye

        arrowImage.layer.addAnimation(anim, forKey: nil)

        //取消动画

        arrowImage.layer.removeAllAnimations()

        //这个是旋转方向的动画

        UIView.animateWithDuration(0.2) { () -> Void in

            //指定旋转角度是180°

            self.arrowImage.transform = CGAffineTransformRotate(self.arrowImage.transform, CGFloat(M_PI))

        }

    }

 

    // 旋转动画二

    func rotateArrow() {

        UIView.animateWithDuration(0.3, animations: {[weak self] () -> () in

            if let selfie = self {

                selfie.arrowImage.transform = CGAffineTransformRotate(selfie.arrowImage.transform, 180 * CGFloat(M_PI/180))

            }

            })

    }

Swift - 点击箭头旋转