美文网首页程序员
88课:手势滑动和摇一揺的实现方法

88课:手势滑动和摇一揺的实现方法

作者: sing_crystal | 来源:发表于2016-06-03 19:44 被阅读80次

    课程笔记文集地址:Udemy课程:The Complete iOS 9 Developer Course - Build 18 Apps

    这节课没有用到 Storyboard,全部用代码实现的。

    滑动手势

    创建手势只需要三行代码(关键点是 UISwipeGestureRecognizer):

    // 一:创建滑动手势
    let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.swiped(_:)))
    // 二:设置手势滑动的方向
    swipeRight.direction = UISwipeGestureRecognizerDirection.Right
    // 三:把手势添加到当前界面
    self.view.addGestureRecognizer(swipeRight)
            
    //再创建一个上滑的手势
    let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.swiped(_:)))
    swipeUp.direction = UISwipeGestureRecognizerDirection.Up
    self.view.addGestureRecognizer(swipeUp)
    

    给手势添加方法:

    func swiped(gesture: UIGestureRecognizer) {
        if let swipeGesture = gesture as? UISwipeGestureRecognizer {
            switch swipeGesture.direction {
                case UISwipeGestureRecognizerDirection.Right:
                  print("User swiped Right")
                case UISwipeGestureRecognizerDirection.Up:
                  print("User swiped Up")
                default:
                  break
            }
        }
    }
    

    摇一摇

    摇一摇比手势简单多了,代码如下:

    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
        if event?.subtype == UIEventSubtype.MotionShake {
            // 在这里写摇一摇之后要执行的事件
            print("Device was shaken")
        }
    }
    

    相关文章

      网友评论

        本文标题:88课:手势滑动和摇一揺的实现方法

        本文链接:https://www.haomeiwen.com/subject/xlhxdttx.html