我创建了一个带有 @IBOutlet
属性“标签”的自定义 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!
}
主 Storyboard
<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
最佳答案
如果您在 Storyboard中使用原型(prototype)单元格并在其中定义单元格的内容和连接,则必须从 TableView 中获取该“准备好的”单元格的副本。您不能只创建一个新的单元格对象并期望它工作(您得到的是一个“原始”实例,而不是没有建立任何连接)
您要做的是在 Interface Builder 中设置原型(prototype)单元格的标识符(在属性检查器中)。然后,要获取单元格的新实例,只需:
tableView.dequeueReusableCellWithIdentifier("yourIdentifier") as TableViewCell
在您的情况下,您是在 TableView Controller 内部进行此调用,因此只需省略 tableView。
关于uitableview - Swift:无法在自定义 UITableViewCell 中访问 IBOutlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26614450/