2014-10-28 100 views
2

我创建了一个具有@IBOutlet属性'label'的自定义UITableViewCell子类,但是当我在viewDidLoad函数中访问它时它是零。Swift:无法在自定义UITableViewCell中访问IBOutlet

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.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

回答

1

如果您使用的是故事板原型细胞和定义有单元格的内容和连接,你必须从表视图获取“准备”单元的副本。你不能只是创建一个新的对象的单元格,并期望它的工作(你得到一个“原始”的实例,而不是任何连接)

你想要做的是设置原型单元格的标识符在Interface Builder中(它在属性检查器中)。然后,为了获得细胞的新实例,简单地说:

tableView.dequeueReusableCellWithIdentifier("yourIdentifier") as TableViewCell 

在你的情况,你正在做的表视图控制器内这个调用,因此只需要省略tableView.

相关问题