iOS/Swift: How to implement longPressed action for backButton?

≯℡__Kan透↙ 提交于 2020-01-15 08:09:58

问题


I'm trying to implement a custom back button for every ViewController in my app. I want it to have two actions. If the button gets tapped, it should behave normally and go up the navigation stack. If the button gets pressed longer it should go to a predefined ViewController.

How can I achieve this for only the backbutton in swift?


回答1:


You can hide your default navigation back button and add a custom button this way:

import UIKit

class SViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //hide your default back button
        navigationController!.setNavigationBarHidden(false, animated:true)

        //create a new button 
        var myBackButton:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        myBackButton.addTarget(self, action: "popToRoot:", forControlEvents: UIControlEvents.TouchUpInside)
        myBackButton.setTitle("Back", forState: UIControlState.Normal)
        myBackButton.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        myBackButton.sizeToFit()

        //create a LongPressGestureRecognizer
        var longPressGesture = UILongPressGestureRecognizer(target: self, action: "longPressAction:")

        //add LongPressGestureRecognizer into button
        myBackButton.addGestureRecognizer(longPressGesture)

        var myCustomBackButtonItem:UIBarButtonItem = UIBarButtonItem(customView: myBackButton)
        self.navigationItem.leftBarButtonItem  = myCustomBackButtonItem

    }

    //this method will call when you tap on button.
    func popToRoot(sender:UIBarButtonItem){
        self.navigationController!.popToRootViewControllerAnimated(true)
    }

    //this method will call when you long press on button
    func longPressAction(gestureRecognizer:UIGestureRecognizer) {

        //initiate your specific viewController here.
        println("Long press detected")
    }

}


来源:https://stackoverflow.com/questions/32517434/ios-swift-how-to-implement-longpressed-action-for-backbutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!