我尝试从两个类函数访问变量“ viewControllers”,但是我总是在图片上看到错误。
如何解决从viewDidLoad()访问变量以使用Tabman在两个ContainerView之间切换的问题?
答案 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
}