I need to load a custom cell in a UITableView. I created a custom subclass of UITableViewCell named "CustomTableViewCell". I have added a UITabelViewCell to the tableview (using drag and drop) as shown in figure. Then in file inspector I set the class of that UITabelViewCell to be "CustomTableViewCell". Here is my code:
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet var tableView : UITableView
var items = String[]()
override func viewDidLoad() {
super.viewDidLoad()
items = ["Hi","Hello","How"]
self.tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "CusTomCell")
// Do any additional setup after loading the view, typically from a nib.
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{
return items.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{
var cell:CustomTableViewCell? = self.tableView.dequeueReusableCellWithIdentifier("CusTomCell") as? CustomTableViewCell
if !cell
{
cell = CustomTableViewCell(style: UITableViewCellStyle.Subtitle,
reuseIdentifier: "CusTomCell")
}
println("cell (cell)")
// cell.?.labelTitle.text = items[indexPath.row]
cell!.labelTitle.text = "some text"
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
When I run my code, I get the following error: "fatal error: Can't unwrap Optional.None" as seen in the image.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…