【问题标题】:Change the tabs in a Embedded TabBarController更改 Embedded TabBarController 中的选项卡
【发布时间】:2021-04-15 21:14:24
【问题描述】:

我有一个视图控制器,它有两个按钮和一个嵌入式 TabBarController。 我想使用两个按钮而不是标签栏项目。并且由于某种原因无法使其工作。

主视图

import UIKit

class ViewController: UIViewController {
    
    var currentTab = 0
    
    @IBOutlet weak var container: UIView!
    
    @IBAction func item1Button(_ sender: UIButton) {
        currentTab = 0
    }
    
    @IBAction func item2Button(_ sender: UIButton) {
        currentTab = 1
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toControllers"{
            if let vc = segue.destination as? TabsViewController {
                vc.selectedIndex = currentTab

            }
        }
    }
}

标签栏控制器

import UIKit

class TabsViewController: UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

故事板中有两个项目,所以项目 0 和 1 应该没问题。

可能很简单,自己想不通。

谢谢!

【问题讨论】:

  • 在我的脑海中,一些想法。 (1) 您是否设置了断点以确保vc.selectedTab = currentTab 被命中? (2) 您是否尝试过“精简”您的代码。我看到了对导航控制器、segue、IBOutlets、IBActions 的引用。似乎您的代码中有很多可能的故障点。 (3)你试过didSet而不是willSet吗?你知道这是不是问题所在?
  • 它被击中,但在第一次初始化后没有更新。
  • 我更新了一点代码,去掉了 TabController 中的变量,它只是在第一次初始化时被触发,所以它没有做太多。

标签: swift uikit uitabbarcontroller


【解决方案1】:

我想通了,解决办法如下:

将主控制器更改为:

class ViewController: UIViewController {
    
    var currentTab = 1
    private var tabViewController: UITabBarController?
    
    @IBOutlet weak var container: UIView!
    
    @IBAction func item1Button(_ sender: UIButton) {
        print("click item1")
        tabViewController?.selectedIndex = 0
    }
    
    @IBAction func item2Button(_ sender: UIButton) {
        print("click item2")
        tabViewController?.selectedIndex = 1
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toControllers"{
            if let vc = segue.destination as? TabsViewController {
                tabViewController = vc
            }
        }
    }

【讨论】:

    猜你喜欢
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 2016-01-08
    相关资源
    最近更新 更多