Swift - Delegate function not returning value

squarehippo10

VC-A is embedded in a nav controller and has a button going to VC-B via a popover segue. VC-B has a table view with a few font names. When I select a font name, VC-B closes and, using delegate/protocol, VC-A should get the selected name. It does not. I found that if I set a breakpoint at the end of didSelectRowAt, delegate is nil for some reason.

VC-A

class ViewController: UIViewController, FontDelegate {
    @IBOutlet weak var infoLabel: UILabel!
    let fontTable = FontTableTableViewController()

    override func viewDidLoad() {
        super.viewDidLoad()
        fontTable.delegate = self
    }
    
    func getFontName(data: String) {
        infoLabel.text = data
    }
}

VC-B

protocol FontDelegate {
    func getFontName(data: String)
}
    
class FontTableTableViewController: UITableViewController {

   let fontArray = ["Helvetica", "Arial", "Monaco"]
   var delegate: FontDelegate?

   // MARK: - Table view functions go here...

   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      let font = fontArray[indexPath.row]
      self.delegate?.getFontName(data: font)
      self.dismiss(animated: true, completion: nil)
   }
}

This shows the storyboard connection from the button in VC-A to VC-B.

enter image description here

Amr

Instead of linking Pick your font button to the other controller, I would suggest you creating an IBAction of the button to trigger the following code whenever pressed:

let storyBoard = UIStoryboard(name: "Main", bundle: nil)
guard let vc = storyBoard.instantiateViewController(withIdentifier: "FontScreen") as? FontTableTableViewController else {return}
vc.delegate = self
vc.modalPresentationStyle = .fullScreen
self.navigationController?.pushViewController(vc, animated: true)

but for this to work you will need to go to the identity inspector of your FontTableTableViewController and from there you can name your controller in storyboardID field in Identity section as FontScreen.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related