2

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?

leyke077
  • 59
  • 7

1 Answers1

3

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

}
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165