Home > Enterprise >  How do I add an IBOutlet to subclass in another file?
How do I add an IBOutlet to subclass in another file?

Time:01-07

I going through Apple's book "‎Develop in Swift Data Collections" and the starting point as follows:

We have a table view controller with "Label Outlet"

We have a first Swift file called "EmojiTableViewController" with main class. This class is connected to ViewController

class EmojiTableViewController: UITableViewController {
}

We have a second Swift file called "EmojiTableViewCell" with subclass This class is connected to cell

class EmojiTableViewCell: UITableViewCell {
    @IBOutlet var nameLabel: UILabel!
}

And the goal is to connect IBOutlet in the second file (EmojiTableViewCell) with the Storyboad. The problem is that no matter what I do the "Assistant" opens the main class. How should I change assistant to show subclass or how could I connect outlets via code?

CodePudding user response:

First create an empty XIB file and call it as EmojiTableViewXIB, then add TableViewCell from Xcode library and later set EmojiTableViewCell class to EmojiTableViewXIB.xib file. 

Secondly add below code to TableViewController file:
 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "EmojiTableViewCell", for: indexPath) as! EmojiTableViewCell
        cell.nameLabel.text = "My custom Text"
        return cell
    }
 override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.register(UINib(nibName: "EmojiTableViewCell", bundle: nil), forCellReuseIdentifier: "EmojiTableViewCell")
    }
    
Thirdly add create a Tableview file and set this file to view of TableViewController 

Lastly run you can run the code.

//MARK: You can find running code from the below GitHub repo link.

https://github.com/ahmetbostanciklioglu/IBOutletConnectionsFromCustomTableView.git

  • Related