[英]Swift UITableViewCell subclass, IBOutlet UILabel error, no error if used as normal var
这可能真的很愚蠢,因为我对Swift和iOS开发myCell
,但是我有一个UITableView
并myCell
UITableViewCell
(称为myCell
)。
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
声明为标准var
,则var myLabel: UILabel!
,然后像上面在初始化程序中实例化它一样,一切正常。
如果重要,我将UITableView
放在UIViewController
(而不是UITableViewController
),因此视图控制器将实现UITableViewDataSource
和UITableViewDelegate
,并将表视图添加为子视图。
我的问题是,在通过界面生成器进行操作时,为什么myLabel
可能nil
? (我已经检查了连接,并删除了连接并创建了一个新标签-通过ctrl +从情节UILabel
拖到代码中,然后通过从代码中的圆圈拖动到故事板UILabel
。)
编辑
通过以下方式调用我的表格单元格: let cell = tableView.dequeueReusableCellWithIdentifier("MyTableViewCell", forIndexPath: indexPath) as! MyTableViewCell
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通过特定的redirectIdentifier连接到特定的单元格。 您是否要在与其所在的单元格不同的单元格中访问标签? 这可能会导致您遇到错误。
我弄清楚,有两个问题:
1)我在ViewController子类中没有TableView的出口(@IBOutlet),并且
2)我正在使用let
在ViewController的didLoad中创建一个UITableView
对象,并将dataSource和委托设置为self
, 将其作为子视图添加到ViewController的视图中,显然搞砸了所有东西。
如果还有其他人想这样做,我发现此链接很有帮助: https : //medium.com/@ronm333/a-simple-table-view-example-in-swift-cbf9a405f975#.yymib1tm5
感谢您的帮助, rMickeyD 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.