I have an app with a tableView
. I decided to add more screens with other tableViews
, so I added a tabBarController
programatically. Now I get a found nil error on these lines:
tableView.delegate = self
tableView.dataSource = self
If I remove them, the tableView
doesn't load. Do you know what I might be doing wrong?
I added a tabBarController
on main storyboard an linked it to the swift file, but it also doesn't work.
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
}
The code for the TabBarController
. Do I have to change anything here to specify that the view is a 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)
}
}
}
in class named SecondVC
you have an outlet reference for your UITableView instance this means you create your table view in Stroyboard, so you can not create the view controller using the initializer you should use
UIStoryboard(name: "yourStoryBoardName", bundle: nil).instantiateViewController(withIdentifier: "yourViewcontrollerID")
the setupTabBar function should be as the following
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)
}
}