从类函数内的viewdidLoad()访问变量

时间:2018-08-23 18:22:18

标签: ios swift

我尝试从两个类函数访问变量“ viewControllers”,但是我总是在图片上看到错误。

enter image description here

如何解决从viewDidLoad()访问变量以使用Tabman在两个ContainerView之间切换的问题?

3 个答案:

答案 0 :(得分:5)

您的var viewController声明位于viewDidLoad函数的花括号内,因此它是临时的,其他代码看不到。

var viewController声明上移一个级别,使其成为您的其他方法可以看到的实例属性。

答案 1 :(得分:0)

您应该在类范围内初始化变量。这样的事情。

class YourViewController: UIViewController {

  var viewControllers = [controller1, controller2]

  // your code

}

这不是主题,但我保证会分享一个代码示例,说明如何以编程方式创建TabBarController。

class MainTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupViewControllers()
    }

    private func setupViewControllers() {
        //1st viewController
        let firstViewController = UIViewController()
        firstViewController.view.backgroundColor = .green

        let firstNavController = templateNavController(unselectedImage: UIImage(named: "yourImage"), selectedImage: UIImage(named: "yourImageSelected"), roootViewController: firstViewController)

        //2nd 
        let secondViewController = UIViewController()
        secondViewController.view.backgroundColor = .red

        let secondNavController = templateNavController(unselectedImage: UIImage(named: "yourSecondImage"), selectedImage: UIImage(named: "yourSecondImageSelected"), roootViewController: secondNavController)

        // put your controllers here
        viewControllers = [firstNavController, secondNavController]
    }


    private func templateNavController(unselectedImage: UIImage, selectedImage: UIImage, roootViewController: UIViewController = UIViewController()) -> UINavigationController {
        let viewController = roootViewController
        let navController = UINavigationController(rootViewController: viewController)
        navController.tabBarItem.image = unselectedImage
        navController.tabBarItem.selectedImage = selectedImage
        return navController
    }

}

答案 2 :(得分:0)

使用任何本地或全局编程语言查看所有变量

local是在函数中声明的那些变量,而global变量是在类级别声明的那些变量。

您在函数内声明变量,这意味着对这些变量的访问仅限于在函数中进行。

在类级别声明变量。这是代码-

class TableviewController:UIViewController
{
var whatContentView:UIView!
var whereContentView:UIView!
var viewControllers:[UIView] = [whatContentView,whereContentView]

// your code

}