【问题标题】:Add Tab Bar Programmatically to ViewController以编程方式将选项卡栏添加到 ViewController
【发布时间】:2017-11-24 19:59:28
【问题描述】:

我的Main.storyboard 文件中有一个TabBarController。 在我的Upload.storyboard 中,我从Main.storyboard 文件中展示了一个ViewController,但是,它不包含标签栏。

viewProfile 按钮应转到名为 Sharks 的选项卡,并在其中显示基于在 Upload.storyboard(模态视图)中收集的数据的视图控制器。

我可以通过编程方式添加标签栏还是我没有正确显示正确的 VC?

// MARK: - Actions
@IBAction func viewProfileButtonPressed(_ sender: UIButton) {
    let stb = UIStoryboard(name: "Main", bundle: nil)
    let sharkProfile = stb.instantiateViewController(withIdentifier: "sharkProfile") as! SharkProfileTableViewController
    self.present(sharkProfile, animated: true) {
        // add tab bar here?
    }
}

【问题讨论】:

  • 你想在这里发生什么?您是否从标签栏开始,点击“viewProfile”,然后您想要显示“SharkProfile”代替该标签的当前视图?你想让“SharkProfile”像典型的导航控制器一样从右侧滑入吗?还是您希望“SharkProfile”拥有自己的独立标签栏?
  • 该应用程序以标签栏开始 - 但随后我将呈现一个没有标签栏的模式视图。在这个模态视图中,点击 viewProfile 应该会显示 SharkProfile,因为它在 Main.storyboard 中(带有标签栏)。

标签: ios swift xcode uitabbarcontroller uistoryboard


【解决方案1】:

一种方法是创建一个委托协议以允许点击View Profile 按钮“回调”到呈现它的视图控制器。当收到该回调时,VC 设置“当前”选项卡。

它看起来像这样:

// define "call back" delegate protocol
protocol EncounterUploadedDelegate : class {
    func didTapSharkProfileButton()
}

Encounter 视图控制器需要遵守该协议:

class EncounterViewController: UIViewController, EncounterUploadedDelegate {

    // the normal stuff for this VC and all the other code for it
    // ...

    // conform to the protocol
    func didTapSharkProfileButton() -> Void {
        // when we get this call-back, switch to the Shark Profile tab
        // tabs are zero-based, so assuming "SharkProfile" is
        // is the 4th tab...
        self.tabBarController?.selectedIndex = 3
    }

    // assuming a "Show Modal" segue named "ShowEncounterUploadSegue" is used
    //  to present the Modal View
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ShowEncounterUploadSegue" {
            let vc = segue.destination as! TabModalVC
            vc.encounterDelegate = self
        }
    }

}

要显示为模态的视图控制器:

class TabModalVC: UIViewController {
    weak var encounterDelegate: EncounterUploadedDelegate?

    @IBAction func profileButtonTapped(_ sender: Any) {
        // dismiss self (the modal view)
        self.dismiss(animated: true, completion: nil)
        // this will call back to the delegate, if one has been assigned
        encounterDelegate?.didTapSharkProfileButton()
    }

}

希望一切都有意义:)

【讨论】:

    【解决方案2】:

    您需要做的是呈现标签栏视图控制器,而不是嵌入其中的视图控制器

    【讨论】:

      猜你喜欢
      • 2016-12-30
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多