Reputation: 560
Learning Swift and Storyboards, I'm attempting to create a View of repeating cells (UITableView).
So far I have created a view with a UIView, linked to a UITableView with a UITableViewCell inside. The issue I'm having is my cells are not displaying "woof" as per below.
My View Controller looks like this:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId") as! MyListViewCell
cell.myLabel.text = "woof"
return cell
}
}
After some research, I believe I don't need to register:
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellId")
as it's already linked as an outlet successfully
but I thought I may need to do delegate and datasource like so:
myTableView.datasource = self
myTableView.delegate = self
but I received: Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
I am attempting to use MVVM which I think is meant to only use the one ViewController. Am I meant to be using a UITableViewController instead?
I have verified that my cell identifier is set correctly in the storyboard.
Upvotes: 0
Views: 188
Reputation: 9925
This error in your case can be related to the missing connection between UITableView in a storyboard and your IBOutlet myTableView.
Concerning the UITableView.register(_:forCellIdentifier:) method, when you are creating a cell in UITableView in a storyboard then this method is called by UIKit when loading the storyboard. You should call this method when you have created a custom UITableViewCell subclass in code or Xib file.
Setting delegate and dataSourceDelegate can be done in a storyboard file without creating an IBOutlet in a view controller. Just select Table View and go to the connections inspector and drag a delegate and a datasource delegate to the view controller.
Upvotes: 1
Reputation: 77
Firstly, check if you have connected properly on storyboard(Outlets,identifier everything). Secondly, if nothing works try disconnecting and connecting the Outlets again.
Upvotes: 0