簡體   English   中英

Swift:iOS 使用滑動手勢更改視圖

[英]Swift: iOS changing view using swipe gesture

我是 iOS 開發的新手。

如何實現滑動手勢來來回改變視圖? 迄今為止我見過的最好的例子是 Soundcloud 應用程序,但我不知道如何讓它工作。

與 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
    }
}

使用此代碼...

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
        }
    }
}

您可以將 UISwipeGestureRecognizer 添加到您的 UIView 並添加到此手勢的目標和手勢發生時要執行的操作

 var swipeGesture = UISwipeGestureRecognizer(target: self, action: "doSomething")
 myView.addGestureRecognizer(swipeGesture)

 func doSomething() {

    // change your view's frame here if you want        
 }

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

基本上,您需要在視圖中添加一個手勢識別器來監聽滑動手勢。 然后當它檢測到滑動時,推到下一個視圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM