【问题标题】:Change iOS view / view controller using swipe gesture使用滑动手势更改 iOS 视图/视图控制器
【发布时间】:2015-09-01 17:07:55
【问题描述】:

如何实现滑动手势来来回切换视图?

到目前为止我见过的最好的例子是 Soundcloud 应用程序,但我不知道如何使它工作。

【问题讨论】:

  • 到目前为止您尝试了哪些方法?什么有效,什么无效?
  • UIPageViewController 可以处理滑动和视图转换。

标签: ios swift uiview swipe-gesture


【解决方案1】:

兼容 Swift 5

override func viewDidLoad()
{
    super.viewDidLoad()

    let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(_:)))
    let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(_:)))
    
    leftSwipe.direction = .left
    rightSwipe.direction = .right

    view.addGestureRecognizer(leftSwipe)
    view.addGestureRecognizer(rightSwipe)
}

@objc func handleSwipes(_ sender: UISwipeGestureRecognizer)
{
    if sender.direction == .left
    {
       print("Swipe left")
       // show the view from the right side
    }

    if sender.direction == .right
    {
       print("Swipe right")
       // show the view from the left side
    }
}

【讨论】:

【解决方案2】:

使用此代码...

override func viewDidLoad() {
    super.viewDidLoad()

    var swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
    swipeRight.direction = UISwipeGestureRecognizerDirection.Right
    self.view.addGestureRecognizer(swipeRight)


}

func respondToSwipeGesture(gesture: UIGestureRecognizer) {

    if let swipeGesture = gesture as? UISwipeGestureRecognizer {

        switch swipeGesture.direction {

        case UISwipeGestureRecognizerDirection.Right:

            println("Swiped right")

//change view controllers

    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        let resultViewController = storyBoard.instantiateViewControllerWithIdentifier("StoryboardID") as ViewControllerName

        self.presentViewController(resultViewController, animated:true, completion:nil)    



        default:
            break
        }
    }
}

【讨论】:

    【解决方案3】:

    您可以将 UISwipeGestureRecognizer 添加到您的 UIView 中,并向此手势添加目标和手势发生时要执行的操作

     var swipeGesture = UISwipeGestureRecognizer(target: self, action: "doSomething")
     myView.addGestureRecognizer(swipeGesture)
    
     func doSomething() {
    
        // change your view's frame here if you want        
     }
    

    【讨论】:

      【解决方案4】:

      本教程可能对您有所帮助:http://www.avocarrot.com/blog/implement-gesture-recognizers-swift/

      基本上,您需要在视图中添加一个手势识别器来监听滑动手势。然后当它检测到滑动时,推送到下一个视图。

      【讨论】:

        猜你喜欢
        • 2013-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多