Ios 具有nil UIImageView的自定义UITableViewCell

Ios 具有nil UIImageView的自定义UITableViewCell,ios,swift,xcode,uitableview,Ios,Swift,Xcode,Uitableview,我创建了一个UITableView,下面是我的代码: func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ // let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "SubjectCell") let cell = Subje

我创建了一个UITableView,下面是我的代码:

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与我的原型细胞相连


解包是由Xcode完成的,它不应该为零,因为它实际上是一个单元格UIImageView。

自从iOS storyboard design发布以来,您不再需要为UITableViewCell创建子类来创建自定义单元格

在情节提要中,选择原型单元,在“属性检查器”选项卡中,为自定义单元指定一个标识符,例如:YourCellIdentifier

接下来,仍然在故事板中选择添加到自定义单元格的UIImageView,为其指定一个标记号,例如:1000

现在将此代码添加到cellForRowAt方法:


为什么您不能从表视图中正确地将单元格出列?@rmaddy没有特别的原因。这是一个非常原始的代码,我通常会在以后修改它。。。然而,我觉得这不是它崩溃的原因,而是它失败的原因。代码不会从xib/情节提要创建单元格。您仅从代码创建单元格。因此,没有设置电池的任何出口。正确创建您的单元格。正确注册cell类/nib,它将按预期工作。如何从故事板创建单元格?我认为使用标识符就足够了,您应该在tableView中使用dequeueReusableCellwithIdentifier:,for:方法,cellForRowAt:。关于如何在web上对可重用单元进行排队,有很多例子。
- (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;
}