Swift自定义后退按钮和目标

时间:2021-04-30 15:38:45

I am currently using SWRevealViewController for a sidebar menu in my app. When I click one of the options, the destination view controller doesn't have a 'back' button because it hasn't come from a proper view controller (i.e. page to go back to).

我目前正在使用SWRevealViewController作为我的应用程序中的侧边栏菜单。当我单击其中一个选项时,目标视图控制器没有“后退”按钮,因为它不是来自正确的视图控制器(即要返回的页面)。

Therefore I am wanting to manually create a back button on the destination view controller which will go back to the home view controller.

因此,我想在目标视图控制器上手动创建一个后退按钮,它将返回到主视图控制器。

I have looked at the code here: How do I manually set the "Back" destination in iOS apps

我在这里查看了代码:如何在iOS应用程序中手动设置“返回”目标

But I am struggling to implement this in Swift (one error after another!). Any help? Thanks!

但我正在努力在Swift中实现这个(一个又一个错误!)。有帮助吗?谢谢!

EDIT

编辑

I have tried the suggestion below, but the back button just doesn't appear. This may have something to with the fact I have the navbar hidden in other views and do the following on the destination view:

我已经尝试了下面的建议,但后面的按钮没有出现。这可能与我在其他视图中隐藏导航栏并在目标视图上执行以下操作有关:

override func viewDidLoad() {
    super.viewDidLoad()
    navigationController.setNavigationBarHidden(false, animated:true)
    var myBackButton:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
    myBackButton.addTarget(self, action: "popToRoot:", forControlEvents: UIControlEvents.TouchUpInside)

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

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func popToRoot(sender:UIBarButtonItem){
    self.navigationController.popToRootViewControllerAnimated(true)
}

Not sure why the back button won't show up?

不确定为什么后退按钮不会显示?

Edit

编辑

This is the prepareForSegue from my sidebar view controller. If there is a way to check for the segue identifier 'test' then I can set the back button from here?

这是我的侧边栏视图控制器中的prepareForSegue。如果有办法检查segue标识符'test',那么我可以从这里设置后退按钮?

- (void) prepareForSegue: (UIStoryboardSegue *) segue sender: (id) sender
{
// Set the title of navigation bar by using the menu items
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
UINavigationController *destViewController = (UINavigationController*)segue.destinationViewController;
destViewController.title = [[_menuItems objectAtIndex:indexPath.row] capitalizedString];


if ( [segue isKindOfClass: [SWRevealViewControllerSegue class]] ) {
    SWRevealViewControllerSegue *swSegue = (SWRevealViewControllerSegue*) segue;

    swSegue.performBlock = ^(SWRevealViewControllerSegue* rvc_segue, UIViewController* svc, UIViewController* dvc) {

        UINavigationController* navController = (UINavigationController*)self.revealViewController.frontViewController;
        [navController setViewControllers: @[dvc] animated: NO ];
        [self.revealViewController setFrontViewPosition: FrontViewPositionLeft animated: YES];
    };

}

}

4 个解决方案

#1


24  

You can write that in swift like this

你可以像这样快速写出来

Write this to add button on navigationController

写这个以在navigationController上添加按钮

    navigationController.setNavigationBarHidden(false, animated:true)
    var myBackButton:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
    myBackButton.addTarget(self, action: "popToRoot:", forControlEvents: UIControlEvents.TouchUpInside)
    myBackButton.setTitle("YOUR TITLE", forState: UIControlState.Normal)
    myBackButton.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
    myBackButton.sizeToFit()
    var myCustomBackButtonItem:UIBarButtonItem = UIBarButtonItem(customView: myBackButton)
     self.navigationItem.leftBarButtonItem  = myCustomBackButtonItem

this will pops to rootViewController

这将弹出到rootViewController

    func popToRoot(sender:UIBarButtonItem){
       self.navigationController.popToRootViewControllerAnimated(true)
    }

#2


5  

In Swift 2.1

在Swift 2.1中

I am customizing Navigation Bar Items this way

我这样定制导航栏项目

  • I can change Navigation bar background image, title text, text color
  • 我可以更改导航栏背景图像,标题文本,文本颜色
  • I can show/hide back button
  • 我可以显示/隐藏后退按钮
  • I can Change Title/ Icon or custom action method
  • 我可以更改标题/图标或自定义操作方法

In AppDelegate I have

在AppDelegate我有

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
    {
        //Cutomize navigation bar
        let navBgImage:UIImage = UIImage(named: "dummy_navigation_bg_image")!
        UINavigationBar.appearance().setBackgroundImage(navBgImage, forBarMetrics: .Default)
        UINavigationBar.appearance().tintColor = UIColor.whiteColor()
        UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()];


        return true
    }

In ViewController I update Navigation Items in viewWillAppear method this way

在ViewController中,我以这种方式在viewWillAppear方法中更新导航项

override func viewWillAppear(animated: Bool)
    {
        super.viewWillAppear(animated)
        setupNavigationBar()
    }

    // MARK: - NavigationBar methods
    func setupNavigationBar ()
    {

        //current tab screen title
        tabBarController?.title = "Manage"

        //Hide back button or left bar button
        tabBarController?.navigationItem.leftBarButtonItem = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)

        //custom right bar button
        var image = UIImage(named: "dummy_settings_icon")
        image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
        tabBarController?.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.Plain, target: self, action:  "settingButtonAction")
    }

    func settingButtonAction()
    {
        print("Setting Button tapped")
        performSegueWithIdentifier("loadAccountSettingsSegue", sender: nil)

    }

#3


5  

Swift 3.0 Solution:

Swift 3.0解决方案:

    self.navigationController?.setNavigationBarHidden(false, animated:false)

        //Create back button of type custom

        let myBackButton:UIButton = UIButton.init(type: .custom)
        myBackButton.addTarget(self, action: #selector(ViewController.popToRoot(sender:)), for: .touchUpInside)
        myBackButton.setTitle("Back".localized(), for: .normal)
        myBackButton.setTitleColor(.blue, for: .normal)
        myBackButton.sizeToFit()

       //Add back button to navigationBar as left Button

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



 func popToRoot(sender:UIBarButtonItem){
        _ = self.navigationController?.popToRootViewController(animated: true)
    }

#4


3  

Here's an updated version for Swift 2/2.1:

这是Swift 2 / 2.1的更新版本:

self.navigationController? .setNavigationBarHidden(false, animated:true)
let backButton = UIButton(type: UIButtonType.Custom)
backButton.addTarget(self, action: "methodCall:", forControlEvents: UIControlEvents.TouchUpInside)
backButton.setTitle("TITLE", forState: UIControlState.Normal)
backButton.sizeToFit()
let backButtonItem = UIBarButtonItem(customView: backButton)
self.navigationItem.leftBarButtonItem = backButtonItem

#1


24  

You can write that in swift like this

你可以像这样快速写出来

Write this to add button on navigationController

写这个以在navigationController上添加按钮

    navigationController.setNavigationBarHidden(false, animated:true)
    var myBackButton:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
    myBackButton.addTarget(self, action: "popToRoot:", forControlEvents: UIControlEvents.TouchUpInside)
    myBackButton.setTitle("YOUR TITLE", forState: UIControlState.Normal)
    myBackButton.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
    myBackButton.sizeToFit()
    var myCustomBackButtonItem:UIBarButtonItem = UIBarButtonItem(customView: myBackButton)
     self.navigationItem.leftBarButtonItem  = myCustomBackButtonItem

this will pops to rootViewController

这将弹出到rootViewController

    func popToRoot(sender:UIBarButtonItem){
       self.navigationController.popToRootViewControllerAnimated(true)
    }

#2


5  

In Swift 2.1

在Swift 2.1中

I am customizing Navigation Bar Items this way

我这样定制导航栏项目

  • I can change Navigation bar background image, title text, text color
  • 我可以更改导航栏背景图像,标题文本,文本颜色
  • I can show/hide back button
  • 我可以显示/隐藏后退按钮
  • I can Change Title/ Icon or custom action method
  • 我可以更改标题/图标或自定义操作方法

In AppDelegate I have

在AppDelegate我有

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
    {
        //Cutomize navigation bar
        let navBgImage:UIImage = UIImage(named: "dummy_navigation_bg_image")!
        UINavigationBar.appearance().setBackgroundImage(navBgImage, forBarMetrics: .Default)
        UINavigationBar.appearance().tintColor = UIColor.whiteColor()
        UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()];


        return true
    }

In ViewController I update Navigation Items in viewWillAppear method this way

在ViewController中,我以这种方式在viewWillAppear方法中更新导航项

override func viewWillAppear(animated: Bool)
    {
        super.viewWillAppear(animated)
        setupNavigationBar()
    }

    // MARK: - NavigationBar methods
    func setupNavigationBar ()
    {

        //current tab screen title
        tabBarController?.title = "Manage"

        //Hide back button or left bar button
        tabBarController?.navigationItem.leftBarButtonItem = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)

        //custom right bar button
        var image = UIImage(named: "dummy_settings_icon")
        image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
        tabBarController?.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.Plain, target: self, action:  "settingButtonAction")
    }

    func settingButtonAction()
    {
        print("Setting Button tapped")
        performSegueWithIdentifier("loadAccountSettingsSegue", sender: nil)

    }

#3


5  

Swift 3.0 Solution:

Swift 3.0解决方案:

    self.navigationController?.setNavigationBarHidden(false, animated:false)

        //Create back button of type custom

        let myBackButton:UIButton = UIButton.init(type: .custom)
        myBackButton.addTarget(self, action: #selector(ViewController.popToRoot(sender:)), for: .touchUpInside)
        myBackButton.setTitle("Back".localized(), for: .normal)
        myBackButton.setTitleColor(.blue, for: .normal)
        myBackButton.sizeToFit()

       //Add back button to navigationBar as left Button

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



 func popToRoot(sender:UIBarButtonItem){
        _ = self.navigationController?.popToRootViewController(animated: true)
    }

#4


3  

Here's an updated version for Swift 2/2.1:

这是Swift 2 / 2.1的更新版本:

self.navigationController? .setNavigationBarHidden(false, animated:true)
let backButton = UIButton(type: UIButtonType.Custom)
backButton.addTarget(self, action: "methodCall:", forControlEvents: UIControlEvents.TouchUpInside)
backButton.setTitle("TITLE", forState: UIControlState.Normal)
backButton.sizeToFit()
let backButtonItem = UIBarButtonItem(customView: backButton)
self.navigationItem.leftBarButtonItem = backButtonItem