我正在尝试使用自定义选项卡viewController,用户可以在其中按自己的喜好添加/重新排列它们。在下面的代码中,我只需要返回数组计数并显示数组项,就设法通过数组的数目来做到这一点,但是当将其用作单个数组代码时,它仅显示一个视图控制器!
这里是代码:
class ContainerController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
let selectedViewControllers = [Home(),Index(),Favourite(),Library()]
let selectedViewControllersProperties = ["Home","Index","Favourite","Library"]
viewControllers = [createController(title: "\(selectedViewControllersProperties[0])".localized, imageName: "\(selectedViewControllersProperties[0])", vc: selectedViewControllers[0]),
createController(title: "\(selectedViewControllersProperties[1])", imageName: "\(selectedViewControllersProperties[1])", vc: selectedViewControllers[1]),
createController(title: "\(selectedViewControllersProperties[2])", imageName: "\(selectedViewControllersProperties[2])", vc: selectedViewControllers[2]),
createController(title: "\(selectedViewControllersProperties[3])", imageName: "\(selectedViewControllersProperties[3])", vc: selectedViewControllers[3]),]
}
// MARK: - Handlers
func createController(title: String, imageName: String, vc: UIViewController) -> UINavigationController{
let recentVC = UINavigationController(rootViewController: vc)
recentVC.tabBarItem.title = title
recentVC.tabBarItem.image = UIImage(named: imageName)
return recentVC
}
}
当尝试使用此数组时,它仅显示一个viewController:
let tabCount = selectedViewControllersProperties.count - 1
for i in 0...tabCount {
viewControllers = [createController(title: "\(selectedViewControllersProperties[i])".localized, imageName: "\(selectedViewControllersProperties[i])", vc: selectedViewControllers[i])]
}
我在这里做错了,请帮助我解决它。
在for循环的每次迭代中,您只是将一个新数组(仅包含一项)设置为viewControllers
,这就是viewControllers
最后也只包含一项的原因。
您需要将新的VC append
放入阵列,而不是使用=
:
let tabCount = selectedViewControllersProperties.count
// ..< is safer
var viewControllers = [] // you don't seem to have declared this beforehand.
for i in 0..<tabCount {
viewControllers.append(createController(title: "\(selectedViewControllersProperties[i])".localized, imageName: "\(selectedViewControllersProperties[i])", vc: selectedViewControllers[i]))
}
您也可以使用map
:
viewControllers = (0..<tabCount).map {
createController(title: "\(selectedViewControllersProperties[$0])".localized, imageName: "\(selectedViewControllersProperties[$0])", vc: selectedViewControllers[$0])
}