简体   繁体   English

自定义UITableViewCell与零UIImageView

[英]Custom UITableViewCell with nil UIImageView

I created a UITableView and this is my code for it: 我创建了一个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
}

And my SubjectCell class is the following: 我的SubjectCell类如下:

import Foundation
import UIKit

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

However, when I run this code, it crashes. 但是,当我运行此代码时,它崩溃了。 Debugging, I noticed that cellUIImage is nil, so it crashes when it unwraps it. 调试时,我注意到cellUIImage为nil,因此在解开包装时它会崩溃。 The IBOulet is linked to my prototype cell. IBOulet链接到我的原型单元。

链接的UIImageView

The unwrapping thing is made by Xcode, and it shouldn't be nil because it is actually a cell UIImageView . 解包的东西是Xcode制作的,它不应该是nil,因为它实际上是一个UIImageView单元。

Since the release of iOS storyboard design, you no longer have to subclass UITableViewCell to create your custom cell. 自iOS故事板设计发布以来,您不再需要UITableViewCell来创建自定义单元。

In your storyboard, select the Prototype Cell, in the Attributes Inspector tab, give the custom cell an identifier (for example: "YourCellIdentifier"). 在情节提要中,选择“原型单元”,在“属性”检查器选项卡中,为自定义单元指定一个identifier (例如:“ YourCellIdentifier”)。

Next, (still in storyboard) select the UIImageView that you added to the custom cell, give it a tag number (for example: 1000) 接下来,(仍在情节提要中)选择添加到自定义单元格的UIImageView,为其赋予标签号(例如:1000)

Now add this code to cellForRowAt method: 现在,将此代码添加到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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM