【问题标题】:Can't get a back button on my view controller in Swift无法在 Swift 中的视图控制器上获得后退按钮
【发布时间】:2015-07-30 19:08:35
【问题描述】:

这是怎么回事:

我有一个导航控制器,其中 A-TableViewController 设置为根视图控制器。一旦我单击 A 中的一个单元格,它将带我到 B-ViewController。导航控制器有一个标识符“MessagesViewController”。到目前为止,这是我在 A-TableViewController 中的代码:

func tableView (tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let sb = UIStoryboard(name: "Main", bundle: nil)
    let messagesVC = sb.instantiateViewControllerWithIdentifier("MessagesViewController") as! MessagesViewController
    //Some code here
    //This has a back button, but nothing else
    self.navigationController?.pushViewController(messagesVC, animated: true)
    //This has no back button, but everything else that I intended works
    self.navigationController?.presentViewController(messagesVC, animated: true, completion: nil)

我希望能够在一切正常的情况下返回 A-TableViewController。是我推动/呈现视图控制器的方式搞砸了它吗?任何人都知道为什么我在过去 3 天里一直卡在这个问题上?

【问题讨论】:

  • 我想也许你可能想在 A 和 B 之间的故事板中设置一个 segue,然后在你的代码中使用 prepareForSegue 方法
  • 我在 //Some code 中写的实际上是需要从视图 A 传输到视图 B 的数据。所以唯一(据我所知)方法是通过我所拥有的写在我的问题中。如果我可以继续,那就简单多了。
  • 你可以通过 prepareForSegue 方法传递数据,我已经提交了一个可能有帮助的答案
  • 感谢您的回答!但是,@Oscar 的建议可能更容易。如果我能得到一个自定义的后退按钮,那也可以。我添加了一个 self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .Plain, target: self, action: "backButtonPressed") 但它没有出现。有什么线索吗?

标签: ios swift uinavigationcontroller


【解决方案1】:

当您将视图推送到导航视图时,您会获得内置的后退按钮。 presentViewController 以模态方式显示您的视图。我过去所做的是将我自己的后退按钮添加到视图并呈现它。然后当你按下它时,你会调用dismissViewController。

【讨论】:

  • 我尝试添加一个自定义按钮(条形按钮项)并将其显示在屏幕的左上/右上方。但它没有显示。有什么想法吗?
【解决方案2】:

在展示你的 B-ViewController 之后在 viewDidLoad 中试试这个:

let btnBack = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(dismissVC))
    btnBack.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: .normal)
    navigationItem.setLeftBarButton(btnBack, animated: true)

@objc func dismissVC() {
    self.dismiss(animated: true, completion: nil)
}

【讨论】:

    【解决方案3】:

    您可以使用 prepareForSegue 方法来传递数据,如下所示:

    override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
        if segue.identifier == "messageSegue" {
            let vc:  B-ViewController = segue.destinationViewController as!  B-ViewController
            //then set properties of your new viewController like this
            vc.property = dataToPass
        }
    }
    

    【讨论】:

      【解决方案4】:

      如果您确实在使用导航控制器,那么您的问题应该很简单。 创建一个@IBAction,并在其中调用popToRootViewControllerAnimated,如下所示:

       @IBAction func rootButton(sender: UIButton) {
          navigationController?.popToRootViewControllerAnimated(true) // or false :)
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-23
        • 2012-08-11
        • 1970-01-01
        • 2016-06-05
        相关资源
        最近更新 更多