2014-10-28 46 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.

相關問題