我创建了一个带有@IBOutlet
属性"label"的自定义UITableViewCell
子类,但当我在viewDidLoad
函数中访问它时,它为零。
TableViewController.swift
import UIKit
class TableViewController: UITableViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
var cell = TableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:nil)
println(cell.label) // nil
}
}
TableViewCell.swift
import UIKit
class TableViewCell:UITableViewCell
{
@IBOutlet weak var label: UILabel!
}
Main.故事板
<tableViewCell contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="TableViewCell" id="cNV-ZQ-ovR" customClass="TableViewCell" customModule="SimpleTable" customModuleProvider="target">
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="cNV-ZQ-ovR" id="3Qh-aQ-Ys2">
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="H9h-90-Iff">
<rect key="frame" x="15" y="12" width="252" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
</tableViewCellContentView>
<connections>
<outlet property="label" destination="H9h-90-Iff" id="tMj-pZ-Ad2"/>
</connections>
</tableViewCell>
Xcode 6.1 build6A1052d
如果您在故事板中使用原型单元格,并在那里定义单元格的内容和连接,则必须从表视图中获得"准备好的"单元格的副本。你不能只创建一个单元格的新对象并期望它工作(你得到的是一个"原始"实例,而没有任何连接)
您想要做的是在接口生成器中设置原型单元的标识符(它在属性检查器中)。然后,要获得细胞的新实例,只需:
tableView.dequeueReusableCellWithIdentifier("yourIdentifier") as TableViewCell
在您的情况下,您在表视图控制器内部进行此调用,因此只需省略tableView.