应该配置自定义CollectionViewCell的ImageView为零

时间:2016-10-23 14:19:36

标签: ios swift uiimageview uicollectionview uicollectionviewcell

我有tableViewCell collectionViewcollectionView's cells是自定义的,只包含imageView

Here is my test project

以下是我DataSource所需的CollectionView class方法:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell

    let image = UIImage(named: listItems[indexPath.row])
    cell.testImageView.image = image

    return cell
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return listItems.count
}

当我尝试为单元格的imageView设置图像时,我得到了error

  

致命错误:在解包可选值时意外发现nil

我已检查image,它不是nil,但testImageView是,当我尝试将图像设置为collectionViewCell的testImageView时,我收到此错误。 我该如何解决? 的 EDIT1 enter image description here

以下是从tableViewController调用以填充collectionView' s listItem

的方法
func load(listItem: [String]) {
    self.listItems = listItem
    reloadData()

}

此外,如果我使用此collectionView cellForItemAt indexPath删除代码,则一切正常

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath)
let imageView = UIImageView(image:UIImage(named: listItems[indexPath.row]))

cell.backgroundView = imageView

3 个答案:

答案 0 :(得分:2)

你错了两个视图控制器。您的IB插座连接到不同视图控制器中的单元。我的意思是你可以在连接到同一个IBOutlet的不同控制器中拥有多个视图,但在你的情况下,首先加载的那个没有连接,所以这就是它崩溃的原因。

这是您的插座连接的单元格。 This is the cell your outlet was connected to.

这是您尝试加载(但没有将IBOutlet连接到图像视图):

enter image description here

答案 1 :(得分:1)

以防您想要使用代码..

import UIKit


class ImageCell : UICollectionViewCell {

    private var imageView: UIImageView!
    private var descLabel: UILabel!

    public var image: UIImage? {
        get {
            return self.imageView.image
        }

        set {
            self.imageView.image = newValue
        }
    }

    public var imageDesc: String? {
        get {
            return self.descLabel.text
        }

        set {
            self.descLabel.text = newValue
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.initControls()
        self.setTheme()
        self.doLayout()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.initControls()
        self.setTheme()
        self.doLayout()
    }

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

    func initControls() {
        self.imageView = UIImageView()
        self.descLabel = UILabel()
    }

    func setTheme() {
        self.imageView.contentMode = .scaleAspectFit

        self.descLabel.numberOfLines = 1
        self.descLabel.lineBreakMode = .byWordWrapping
        self.descLabel.textAlignment = .center
        self.descLabel.textColor = UIColor.black

        self.contentView.backgroundColor = UIColor.white
    }

    func doLayout() {
        self.contentView.addSubview(self.imageView)
        self.contentView.addSubview(self.descLabel)

        self.imageView.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 5).isActive = true
        self.imageView.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: -5).isActive = true
        self.imageView.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 0).isActive = true

        self.descLabel.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 5).isActive = true
        self.descLabel.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: -5).isActive = true
        self.descLabel.topAnchor.constraint(equalTo: self.imageView.bottomAnchor, constant: 5).isActive = true
        self.descLabel.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -5).isActive = true

        for view in self.contentView.subviews {
            view.translatesAutoresizingMaskIntoConstraints = false
        }
    }
}


class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    private var collectionView: UICollectionView!
    private var dataSource: Array<String>!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.initDataSource()
        self.initControls()
        self.setTheme()
        self.registerClasses()
        self.doLayout()
    }

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

    func initDataSource() {
        self.dataSource = ["Image1", "Image2", "Image3", "Image4", "Image5", "Image6"]
    }

    func initControls() {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 117, height: 125)
        layout.invalidateLayout()
        self.collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
    }

    func setTheme() {
        self.collectionView.backgroundColor = UIColor.clear

        self.edgesForExtendedLayout = UIRectEdge(rawValue: 0)
        self.view.backgroundColor = UIColor.blue
    }

    func registerClasses() {
        self.collectionView.register(ImageCell.self, forCellWithReuseIdentifier: "ImageCellIdentifier")
    }

    func doLayout() {
        self.view.addSubview(self.collectionView)

        self.collectionView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
        self.collectionView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
        self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true

        for view in self.view.subviews {
            view.translatesAutoresizingMaskIntoConstraints = false
        }
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCellIdentifier", for: indexPath) as! ImageCell

        let imageName = self.dataSource[indexPath.row]
        cell.image = UIImage(named: imageName)
        cell.imageDesc = imageName

        return cell
    }
}

http://imgur.com/o7O7Plw

enter image description here

答案 2 :(得分:0)

可能没有从界面构建器连接“testImageView”出口变量,或者没有带有reuseIdentifier“ImageCell”的CollectionViewCell。使用LLDB po命令检查单元格是否为零。