我有一个带有 tableView
的应用程序。我决定用其他 tableViews
添加更多屏幕,所以我以编程方式添加了一个 tabBarController
。现在我在这些行上得到一个found nil error:
tableView.delegate = self
tableView.dataSource = self
如果我删除它们,tableView
不会加载。你知道我可能做错了什么吗?
我在主 Storyboard上添加了一个 tabBarController
并将其链接到 swift 文件,但它也不起作用。
class SecondVC: UIViewController,UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var SoundsClasss = [SoundsClass]()
override func viewDidLoad() {
super.viewDidLoad()
let p1 = SoundsClass(imageURL: "sound 01", audioURL: "01", videoTitle: "1", duration: 100)
let p2 = SoundsClass(imageURL: "sound 01", audioURL: "02", videoTitle: "2", duration: 100)
SoundsClasss.append(p1)
SoundsClasss.append(p2)
tableView.delegate = self
tableView.dataSource = self
}
TabBarController
的代码。我是否必须在此处更改任何内容以指定该 View 是 tableView
?
class MainTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
tabBar.barTintColor = UIColor.white
setupTabBar()
}
func setupTabBar(){
let FirstController = UINavigationController(rootViewController: MainVC())
let SecondController = UINavigationController(rootViewController: SecondVC())
let ThirdController = UINavigationController(rootViewController: ThirdVC())
viewControllers = [FirstController, SecondController,ThirdController]
guard let items = tabBar.items else { return }
for item in items {
item.imageInsets = UIEdgeInsets(top: 4, left: 0, bottom: -4, right: 0)
}
}
}
最佳答案
在名为 SecondVC
的类中,您有一个 UITableView 实例的导出引用,这意味着您在 Stroyboard 中创建了 TableView ,因此您不能使用应该使用的初始化程序创建 View Controller
UIStoryboard(name: "yourStoryBoardName", bundle: nil).instantiateViewController(withIdentifier: "yourViewcontrollerID")
setupTabBar 函数应该如下所示
func setupTabBar(){
let vc1 = UIStoryboard(name: "yourStoryBoardName", bundle: nil).instantiateViewController(withIdentifier: "yourFirstViewcontrollerID")
let vc2 = UIStoryboard(name: "yourStoryBoardName", bundle: nil).instantiateViewController(withIdentifier: "yourSecondViewcontrollerID")
let vc3 = UIStoryboard(name: "yourStoryBoardName", bundle: nil).instantiateViewController(withIdentifier: "yourThirdViewcontrollerID")
let FirstController = UINavigationController(rootViewController: vc1)
let SecondController = UINavigationController(rootViewController: vc2)
let ThirdController = UINavigationController(rootViewController: vc3)
viewControllers = [FirstController, SecondController,ThirdController]
guard let items = tabBar.items else { return }
for item in items {
item.imageInsets = UIEdgeInsets(top: 4, left: 0, bottom: -4, right: 0)
}
}
关于ios - TableViews 不适用于 TabBarController Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56304778/