Kevin Py Kevin Py - 16 days ago 8
iOS Question

Class has no initializers Swift

I have a problem with Swift class. I have a swift file for UITableViewController class and UITableViewCell class. My problem is the UITableViewCell class, and outlets. This class has an error Class "HomeCell" has no initializers, and I don't understand this problem.

Thanks for your responses.

import Foundation
import UIKit

class HomeTable: UITableViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet var tableViex: UITableView!

var items: [(String, String, String)] = [
("Test", "123", "1.jpeg"),
("Test2", "236", "2.jpeg"),
("Test3", "678", "3.jpeg")
]

override func viewDidLoad() {
super.viewDidLoad()

var nib = UINib(nibName: "HomeCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "bookCell")
}

// Number row
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}

// Style Cell
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("bookCell") as UITableViewCell

// Style here

return cell

}

// Select row
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Select
}

}

// PROBLEM HERE
class HomeCell : UITableViewCell {

@IBOutlet var imgBook: UIImageView
@IBOutlet var titleBook: UILabel
@IBOutlet var pageBook: UILabel

func loadItem(#title: String, page: String, image:String) {
titleBook.text = title
pageBook.text = page
imgBook.image = UIImage(named: image)
}

}

Answer

You have to use implicitly unwrapped optionals so that Swift can cope with circular dependencies (parent <-> child of the UI components in this case) during the initialization phase.

@IBOutlet var imgBook: UIImageView!
@IBOutlet var titleBook: UILabel!
@IBOutlet var pageBook: UILabel!

Read this doc, they explain it all nicely.