我有一个tabBar,目前只有一件物品。对于这个项目,我有一个ViewController。
现在,我想要动态添加更多的项目到选项卡栏,这应该都打开相同的ViewController。我将在视图控制器中检查哪个按钮被按下,并自定义内容。
如何将更多项目添加到链接到同一视图控制器的选项卡栏?
我尝试将UITabBarItem
%s添加为列表,但这不起作用。
有什么建议吗?
发布于 2018-10-19 06:40:07
虽然我不喜欢你最初的想法,在tabController中多个相同的VC,但实际上它是可行的。
import UIKit
class MyTabViewController : UIViewController{
override var tabBarItem: UITabBarItem!{
get{ return UITabBarItem.init(title: "temp", image: nil, tag: 100) }
set{ super.tabBarItem = newValue} }
}
class MyTabController: UITabBarController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
perform(#selector(change), with: nil, afterDelay: 3.0)
perform(#selector(printViewController), with: nil, afterDelay: 5.0)
}
@objc func printViewController(){
print (viewControllers!)
}
@objc func change(){
if let viewController = self.viewControllers?[0]{
let label = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 100))
label.text = "testing"
viewController.view.addSubview(label)
setViewControllers([viewController,viewController,viewController,viewController,viewController], animated: true)
}
}
}
5秒后,你可以看到你的tabController中有5个相同的vc。
发布于 2018-10-19 06:15:02
您应该能够继承UITabBarController
的子类,并在viewDidLoad
中使用viewControllers
属性或setViewController(_:animated:)
方法。我建议使用.nib
来布置ViewController
,并使用init(nibName: String?, bundle: Bundle?)
实例化它。
不应该让ViewController
根据它的tabBarItem
属性来确定配置,而应该在设置UITabBarController
的viewController
属性之前进行配置。
大概是这样的:
class TabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
var controllers = [UIViewController]()
let firstViewController = ViewController(nibName: "NIBNAME", bundle: Bundle.main)
// Configure unique properties for firstViewController here, including
// the tabBarItem.
controllers.append(firstViewController)
// Configure the rest of the ViewControllers with unique properties and add them to controllers
setViewControllers(controllers, animated: false)
}
}
另外,请注意,如果您有5个以上的控制器,则需要在UITabBarController子类中使用moreNavigationController
属性。
我建议您使用read the documentation for UITabBarController来了解如何完成所有这些操作。
https://stackoverflow.com/questions/52882686
复制相似问题