SALE: Save 50% on all my books and bundles >>

Day16 -> 100DaysOfSwift - didSelectRowAt problem

Forums > 100 Days of Swift

Hi there,

Currently I'm on 16 day and I'm facing a problem that I cannot resolve at the moment. I'm not doing this course exactly as Paul because I'm not using storyboards. Could anybody check my code and let me know why didSelectRowAt is not taking me onto nextVC ? Within the console I've a message that says that row is tapped. I'm pasting code below:

class ViewController: UIViewController {

  let cellID = "Picture"
  let tableViewCell = TableViewCell()

  let tableWithImages: UITableView = {
    let table = UITableView()
    table.rowHeight = 50
    table.translatesAutoresizingMaskIntoConstraints = false
    return table
  }()

  var pictures: [String] = [String]()

  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    tableWithImages.delegate = self
    tableWithImages.dataSource = self
    tableWithImages.register(TableViewCell.self, forCellReuseIdentifier: cellID)
    fileManagerSetup()
    setupView()
  }

  func fileManagerSetup(){
   let fm = FileManager.default
    let path = Bundle.main.resourcePath!
    let items = try! fm.contentsOfDirectory(atPath: path)
    for item in items {
      if item.hasPrefix("nssl"){
        pictures.append(item)
      }
    }
    print(pictures)
  }

  private func setupView(){
    view.addSubview(tableWithImages)
    tableWithImages.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
    tableWithImages.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
    tableWithImages.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
    tableWithImages.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
  }
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {
   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return pictures.count
  }

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
    cell.textLabel?.text = pictures[indexPath.row]
    return cell
  }

   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let nextVC = DetailViewController()
    nextVC.selectedImage = pictures[indexPath.row]
    self.navigationController?.pushViewController(nextVC, animated: true)
    print("row tapped \(pictures[indexPath.row])")
  }
}

Thank you in advance for your help!!

Ps. I checked on Stackoverflow and within the google but I cannot find the right answer... or maybe I'm to tired ;)

   

@twostraws  Site Admin

If I had to guess, you're missing a navigation controller. Try changing self.navigationController? to self.navigationController! and see if that causes your code to crash.

   

Thanks Paul for the tip however my app crashed when I added "!" to the navigation controller.

Here's the message from console:

["nssl0049.jpg", "nssl0046.jpg", "nssl0091.jpg", "nssl0045.jpg", "nssl0051.jpg", "nssl0041.jpg", "nssl0042.jpg", "nssl0043.jpg", "nssl0033.jpg", "nssl0034.jpg"]
Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/rcebul01/Desktop/DEV/HackingWithSwift/Project1/Project1/ViewController.swift, line 70
2020-03-24 20:20:44.630886+0100 Project1[79158:4679335] Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/rcebul01/Desktop/DEV/HackingWithSwift/Project1/Project1/ViewController.swift, line 70
(lldb) 

I'm pasting also code from DetailViewController.swift

import UIKit

class DetailViewController: UIViewController {

  var imageView: UIImageView = {
    var picture = UIImageView()
    picture.translatesAutoresizingMaskIntoConstraints = false
    return picture
  }()

  var selectedImage: String?

    override func viewDidLoad() {
        super.viewDidLoad()
      view.backgroundColor = .white
      setupView()
      if let imageToLoad = selectedImage {
        imageView.image = UIImage(named: imageToLoad)
      }
    }

  private func setupView(){
    view.addSubview(imageView)
    imageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
    imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
    imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
    imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
  }

}

Thank you in advance for your help :)

   

I found a solution for my problem! Unfortunatelly within mt SceneDelegate.swift I forgot to add navigationController:

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

  var window: UIWindow?

  func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    guard let windowScene = (scene as? UIWindowScene) else { return }
    window = UIWindow(windowScene: windowScene)
    let rootVC = ViewController()
    let nav = UINavigationController(rootViewController: rootVC)
    window?.rootViewController = nav
    window?.makeKeyAndVisible()
  }

Now everything works perfectly :)

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED Building in-app subscriptions are hard. RevenueCat makes it simple. With their open source SDKs, you can painlessly implement subscriptions for your app in hours, not months.

Explore the docs to learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Snapthread is a casual video editor and slideshow maker that makes discovering, compiling and sharing your favorite memories effortless.

 
Unknown user

Not logged in

Log in