Swift - 将单元格customImageView.image设置为nil会导致错误

时间:2015-07-03 08:43:30

标签: swift uitableview uiimageview

我目前正在处理应用的新闻页面,我们在尝试将单元格的customImageView.image设置为nil时遇到了问题,以确保单元格不会加载另一个单元格&#39 ; s图像加载它自己:

cellForRowAtIndexPath(tableView)

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    var requestImg: Alamofire.Request?

    var article : NewsItem
    article = filteredArticles[indexPath.row]
    let imageUrl = NSURL(string: article.image)

    if imageUrl == nil || article.image.isEmpty { newsCellIdentifier = "NewsCellNoImage" }
    else { newsCellIdentifier = "NewsCell" }

    let cell = self.tableView.dequeueReusableCellWithIdentifier(newsCellIdentifier) as! NewsCell

    if (imageUrl != nil || !article.image.isEmpty) {

        cell.customImageView.image = nil // < ISSUE HERE
        requestImg?.cancel()

            requestImg = Alamofire.request(.GET, article.image).responseImage() {
                (request, _, image, error) in
                if error == nil && image != nil {
                    cell.customImageView.image = image
                }
            }
    }

    cell.titleLabel.text = article.title
    cell.categoryLabel.text = article.category

    return cell
}

NewsCell.Swift

class NewsCell: UITableViewCell {

@IBOutlet var titleLabel: UILabel!
@IBOutlet var customImageView: UIImageView!
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var articleTime: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}
}

调用cell.customImageView.image = nil时问题就出现了,我得到了这个问题:fatal error: unexpectedly found nil while unwrapping an Optional value

我看过的每个地方,这是重置UIImageView图像的正确方法,所以我会非常感谢任何出错的帮助。

1 个答案:

答案 0 :(得分:1)

@IBOutlet var customImageView: UIImageView!使用!定义展开值会导致问题。因为如果您使用!转换值,则意味着它不能是nil

使其成为可选项将解决问题

@IBOutlet var customImageView: UIImageView?