我收到错误消息"在展开nil
"时意外找到了Optional
来自Swift,以下课程。错误发生在该行:
(cell.contentView.viewWithTag(1) as UILabel).text = object["firstName"] as? String
我有一个自定义单元格类,其中2个UILabels标记为1和2,出口已设置
import UIKit
import Foundation
class dictionaryTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
var objects = NSMutableArray()
var dataArray = [["firstName":"Debasis","lastName":"Das","email":"debasis_das@knowstack.com"],["firstName":"John","lastName":"Doe","email":"jdoe@knowstack.com"],["firstName":"Jane","lastName":"Doe","email":"janedoe@knowstack.com"],["firstName":"Mary","lastName":"Jane","email":"mjane@knowstack.com"]]
@IBOutlet
var tableView: UITableView!
var items: [String] = ["We", "Heart", "Swift"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count;//self.items.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
//cell.textLabel?.text = self.items[indexPath.row]
//return cell
let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) as UITableViewCell
let object = dataArray[indexPath.row] as NSDictionary
(cell.contentView.viewWithTag(1) as UILabel).text = object["firstName"] as? String
(cell.contentView.viewWithTag(2) as UILabel).text = object["lastName"] as? String
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("You selected cell #\(indexPath.row)!")
}
}
答案 0 :(得分:23)
如果您想使用自定义单元格布局,我建议
子类UITableViewCell
:
// CustomTableViewCell.swift
import UIKit
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var firstNameLabel: UILabel!
@IBOutlet weak var lastNameLabel: UILabel!
}
在故事板中创建表格视图。将单元格原型添加到storyboard中的tableview。设计细胞原型(添加你想要的任何标签)。
将单元格原型的故事板标识符指定为您想要的任何内容(示例中为MyCell
)。
在此示例中,指定单元格原型的基类CustomTableViewCell
:
在您的单元格原型和IBOutlet
子类之间建立UITableViewCell
引用。
请注意IBOutlet
引用左侧的实体项目符号。这表明插座正确连接。
在您的数据源中实施cellForRowAtIndexPath
,例如在Swift 3:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! CustomTableViewCell
let person = dataArray[indexPath.row]
cell.firstNameLabel.text = person["firstName"]
cell.lastNameLabel.text = person["lastName"]
return cell
}
或者在Swift 2中:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) as! CustomTableViewCell
let person = dataArray[indexPath.row]
cell.firstNameLabel.text = person["firstName"]
cell.lastNameLabel.text = person["lastName"]
return cell
}
注意,如果使用单元格原型,则不要在registerClass
中调用viewDidLoad
。故事板将自动为您重新注册您的自定义类以及重用的标识符(因为您在步骤3和步骤4中已完成的操作)。
答案 1 :(得分:5)
EDIT2:这个解决方案可能更适合您的目的。通过这个,您可以为自己的UITableViewCell创建自己的类,并将其用于重用模式。评论在代码中:
class dictionaryTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
// The data
var dataArray = [["firstName":"Debasis","lastName":"Das","email":"debasis_das@knowstack.com"],["firstName":"John","lastName":"Doe","email":"jdoe@knowstack.com"],["firstName":"Jane","lastName":"Doe","email":"janedoe@knowstack.com"],["firstName":"Mary","lastName":"Jane","email":"mjane@knowstack.com"]]
// The outlet to your tableview in the ViewController in storyboard
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Create a nib for reusing
let nib = UINib(nibName: "MyCell", bundle: nil)
// Register the nib for reusing within the tableview with your reuseidentifier
tableView.registerNib(nib, forCellReuseIdentifier: "MyCell")
// Set delegate and datasource to self (you can do that in interface builder as well
tableView.delegate = self
tableView.dataSource = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count; // return the number of datasets
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// create a reusable cell with the reuse identifier you registered in viewDidLoad and cast it to MyCell
let cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as MyCell
let object = dataArray[indexPath.row] as NSDictionary
// set the strings matching your array
cell.label1.text = object["firstName"] as? String
cell.label2.text = object["lastName"] as? String
// return the cell
return cell
}
// some example for the delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("You selected cell #\(indexPath.row)!")
}
}
// class for you own UITableViewCell
// has own xib file
class MyCell: UITableViewCell {
// two outlets representing two labels in the xib file
@IBOutlet private weak var label1: UILabel!
@IBOutlet private weak var label2: UILabel!
}
要使其工作,您必须创建一个具有正确名称的xib文件(在本例中为MyCell)。它应该类似于:
设置自定义视图和插座的类非常重要。
-------------------------------------其他解决方案-------- ------------------------------
编辑:正如我所看到的那样,你没有使用reuseIdentifier'MyCell'初始化你自己的类'MyCell',而是使用Apple的类'UITableViewCell'。这就是使用UITableViewCell的解决方案:行(cell.contentView.viewWithTag(1) as UILabel)
不仅是对特定类的强制转换,它还展开了Optional(UIView)。你在其他情况下用'!'来做到这一点。
所以问题是:你正在创建一个UITableViewCell实例,这是Apple创建的一个类。您希望使用特定标记获取该视图内的子视图。你怎么知道苹果给了他们这些标签?你真正想要的是创建一个具有特殊样式的UITableViewCell实例,并设置textLabels的值,如下所示:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Create an instance of UITableViewCell. Style is .Subtitle but could be others as well
var cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as? UITableViewCell
let object = dataArray[indexPath.row] as NSDictionary
// set the strings matching your array
cell?.textLabel?.text = object["firstName"] as? String
cell?.detailTextLabel?.text = object["lastName"] as? String
// return the cell
return cell!
}
答案 2 :(得分:0)
我所要做的就是:
cell.subviews[0].subviews[0].viewWithTag(//your tag//)