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)
}
}
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.
Quick fix - make sure all variables which do not get initialized when they are created (eg var num : Int?
vs var num = 5
) have either a ?
or !
.
Long answer (reccomended) - read the doc as per mprivat suggests...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With