2017-02-22 65 views
0

我創建了一個UITableView,這是我的代碼吧:自定義的UITableViewCell與零的UIImageView

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ 
    // let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "SubjectCell") 

    let cell = SubjectCell(style: UITableViewCellStyle.default, reuseIdentifier: "SubjectCell") 

    cell.cellUIImage.image = UIImage(named: "menu.png") 

    // cell.cellUIImage = UIImageView(UIImage(named: "menu-32.png")) 

    if indexPath.row % 2 == 0{ 
     cell.backgroundColor = UIColor.cyan 
    } 

    return cell 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return 5 
} 

而且我SubjectCell類如下:

import Foundation 
import UIKit 

class SubjectCell : UITableViewCell{ 
    @IBOutlet var cellUIImage: UIImageView! 
} 

然而,當我運行此代碼,它崩潰。調試,我注意到cellUIImage是零,所以它解開它時崩潰。 IBOulet鏈接到我的原型單元格。

linked UIImageView

解纏的是由Xcode中完成的,它不應該是零,因爲它實際上是細胞UIImageView

+0

爲什麼不正確地從表格視圖中取出單元格? – rmaddy

+0

@rmaddy特別沒有理由。這是一個非常原始的代碼,我通常會在之後對它進行裁剪......但是,我倒下了這不是它崩潰的原因。 –

+2

這正是它失敗的原因。你的代碼不會從你的xib/storyboard創建一個單元格。你只是從代碼創建你的單元格。因此沒有設置單元的出口。正確地創建你的細胞。正確註冊單元類/筆尖,它將按預期工作。 – rmaddy

回答

-2

自iOS故事板設計發佈以來,您不再需要子類UITableViewCell來創建自定義單元格。

在故事板中,選擇原型單元,在屬性檢查器選項卡中,給定製單元一個identifier(例如:「YourCellIdentifier」)。

接下來,(仍然在故事板),選擇您添加到自定義單元格的UIImageView,給它一個標籤編號(例如:1000)

下面這段代碼添加到cellForRowAt方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *cellIdentifier = @"YourCellIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    // Here is your desired image view. 
    UIImageView *yourImageView = [cell viewWithTag:1000]; 

    return cell; 
}