【问题标题】:Setting up the back button in navigation controller在导航控制器中设置后退按钮
【发布时间】:2016-07-18 17:05:31
【问题描述】:

我似乎无法以编程方式正确设置 navigationController 的后退按钮,以显示前一个视图何时使用

self.navigationController?.pushViewController(newView, animated: true)

我使用循环将前一个视图中的所有视图隐藏在viewDidDisappear 中,并且在 viewDidAppear 中呈现的新视图中,我尝试以各种方式设置后退按钮的操作;但是,虽然我可以成功操作自动显示的后退按钮,例如隐藏它或更改它的图像,但我无法设置它的操作。

任何见解都将不胜感激,因为我发现的答案似乎都没有正常工作。这也是在不使用情节提要的情况下完成的

if let img = UIImage(named: "backButton") {
                self.navigationController?.navigationBar.backIndicatorImage = img
                self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = img
                print("IMAGE")
            }
            topItem.backBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Rewind, target: self,
                                                        action:#selector(self.backButtonAction(_:)))

【问题讨论】:

  • 在 ViewDidLoad 或 ViewWillAppear 中更改导航栏图像/文本,而不是在 ViewDidAppear 方法中更改。
  • 它在viewDidAppear中发生了变化,它应该出现在ViewDidLoad中吗?在前一个视图中,导航控制器完全不同,因此我使用 viewDidAppear 和 viewDidDisappear 来显示/隐藏带有控制器的 UIView 和新 UIView 中的 viewDidAppear 来添加一个简单的标题并尝试向后退按钮添加一个功能(自动出现)弹出视图

标签: ios swift uinavigationcontroller


【解决方案1】:

在您的情况下,在导航上添加一个自定义按钮。

class YourViewController: UIViewController {
//Navigation Items.

//left bar button item.
private var leftBarButtonItem : UIBarButtonItem!

//left button.
private var navigationLeftButton : UIButton!

//Your other variable/object declaration.

  func viewDidLoad() {
    super.viewDidLoad()
    self.leftBarButtonItem = UIBarButtonItem()
  }

  func viewDidAppear(animated: Bool) {
      super.viewDidAppear(animated)

      self.setNavigationBackButton()
  }



  private func setNavigationBackButton() {

    if(self.navigationLeftButton == nil) {
        self.navigationLeftButton = UIButton(type: UIButtonType.System)
    }


    //Styling your navigationLeftButton goes here...

    self.navigationLeftButton.addTarget(self, action: Selector("backButtonTapped"), forControlEvents: UIControlEvents.TouchUpInside)
    self.leftBarButtonItem.customView = self.navigationLeftButton
    self.navigationItem.leftBarButtonItem = self.leftBarButtonItem
  }

  func backButtonTapped(AnyObject:sender) {
   // Here add your custom functionalities.
   // Note, this will not pop to previous viewcontroller,

  }
}

【讨论】:

  • 这很好用;我以为我可以利用导航控制器中的后退按钮,因为它没有返回 nil 而是遇到了一些问题。谢谢
猜你喜欢
  • 2023-03-23
  • 2010-11-15
  • 2012-01-01
  • 1970-01-01
  • 2011-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多