My very first attempt at nib based project , here are my steps and a nib area snapshot
Current Error - Thread 1: Exception: "invalid nib registered for identifier (Cell) - nib must contain exactly one top level object which must be a UITableViewCell instance"
Step 1 - I create a nib file called HotelNib and add a viewCotroller
, create a class called HotelViewController: UIViewController
, attach it to the viewController
Step 2 - in the nib add a tableView to viewController, give it constraints
Step 3 - go to SceneDelegate
and add below code as i do not want the storyboard to load , also remove the main from drop-down
guard let winScene = (scene as? UIWindowScene) else { return }
window = UIWindow(windowScene: winScene)
guard let homeController = Bundle.main.loadNibNamed("HotelNib", owner: self, options: nil)?.first as? HotelViewController else { return }
window?.rootViewController = homeController
window?.makeKeyAndVisible()
Step 4 - i run the project, it runs well
Step 5 - add a tableViewCell
in nib area, create a class called ItemViewCell: UITableViewCell
Step 6 - add @IBOutlet weak var tableView: UITableView!
, in HotelView Controller, add delegates and datasource by control + drag from tableView to viewcontroller
Step 7 - Create @IBOutlet weak var nameLabel: UILabel!
in ItemViewCell
Step 8 - My code in HotelViewController, i just cannot get over, error after error about nib not being not able to register , some one please guide here
class HotelViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var restaurantNames = ["Cafe Deadend", "Homei", "Teakha", "Cafe Loisl", "Petite Oyster", "For Kee Restaurant", "Po's Atelier", "Bourke Street Bakery", "Haigh's Chocolate", "Palomino Espresso", "Upstate", "Traif", "Graham Avenue Meats And Deli", "Waffle & Wolf", "Five Leaves", "Cafe Lore", "Confessional", "Barrafina", "Donostia", "Royal Oak", "CASK Pub and Kitchen"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
restaurantNames.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ItemViewCell
cell.nameLabel.text = restaurantNames[indexPath.row]
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
print("right load")
tableView.delegate = self
tableView.dataSource = self
let nib = UINib(nibName: "HotelNib", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "Cell") //always fails here
// Do any additional setup after loading the view.
}
}
Having multiple views in a single .xib file also causes this error. Creating the table view cell in their own separate .xib file will resolve this error.