Swift UITableViewCell 子类,IBOutlet UILabel 错误,如果用作普通 var 则没有错误

Swift UITableViewCell subclass, IBOutlet UILabel error, no error if used as normal var

这可能真的很愚蠢,因为我对 Swift 和 iOS 开发还很陌生,但我有一个 UITableView 并且子类化了 UITableViewCell(称之为 myCell).

myCell在故事板中有一个UILabel,我把它连接到代码中,@IBOutlet weak var myLabel: UILabel!这样下一个小点它是灰色的。然后在初始化程序 override init(style: UITableViewCellStyle, reuseIdentifier: String?) 中,访问 myLabel 时出现以下错误——无论我是否首先实例化它 (myLabel = UILabel()):

fatal error: unexpectedly found nil while unwrapping an Optional value

但是,如果我将myLabel声明为标准varvar myLabel: UILabel!,并在初始化程序中像上面那样实例化它,事情工作。

如果重要的话,我在 UIViewController 中有 UITableView(而不是 UITableViewController),因此视图控制器实现了 UITableViewDataSourceUITableViewDelegate,并将 table 视图添加为子视图。

我的问题是,为什么在通过界面生成器工作时 myLabel 可能会 nil (我已经检查了连接,删除了连接并创建了一个新标签——通过 ctrl+从故事板 UILabel 拖动到代码,并通过从圆圈中拖动来简单地重新连接故事板的代码 UILabel.)

编辑

通过以下方式调用我的 table 单元格: let cell = tableView.dequeueReusableCellWithIdentifier("MyTableViewCell", forIndexPath: indexPath) as! MyTableViewCell 给出以下错误:

'unable to dequeue a cell with identifier MyTableViewCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

...我不明白,因为 "MyTableViewCell" 被设置为故事板中单元格原型的 reuseIdentifier。

故事板中的 UILabel 连接到具有特定 reuseIdentifier 的特定单元格。您是否试图访问与其所在单元格不同的单元格中的标签?这可能会导致您遇到错误。

我弄明白了,有两个问题:

1) ViewController 子类中的 TableView 没有出口 (@IBOutlet),并且

2) 我使用 let 在 ViewController 的 didLoad 中创建一个 UITableView 对象,在将数据源和委托设置为 self 之后,是将它作为子视图 添加到 ViewController 的视图中,显然把一切都搞砸了。

如果其他人想这样做,我发现这个 link 很有帮助: https://medium.com/@ronm333/a-simple-table-view-example-in-swift-cbf9a405f975#.yymib1tm5

感谢您的帮助,rMickeyD