简体   繁体   English

如何在没有Storyboard或笔尖的情况下使用图像初始化collectionViewCell?

[英]How to init collectionViewCell with image without Storyboard or nib?

How to init collection view Cell with image without Storyboard or nib ? 如何在没有Storyboard或笔尖的情况下初始化具有图像的collection view Cell?

I'm building ImagePicker and want to do it without storyboards 我正在构建ImagePicker,并且想要在没有情节提要的情况下进行操作

so the working code with storyboard is like that, but how to do it programmatically ? 所以带有情节提要的工作代码就是这样,但是如何以编程方式进行呢?

class PhotosCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!

    var image: UIImage? {
        get { return imageView.image }
        set { imageView.image = newValue }
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        self.imageView.image = nil
    }

}

My changed code without IBOutlet: 我没有IBOutlet的更改代码:

class PhotosCollectionViewCell: UICollectionViewCell {
    var imageView: UIImageView!
    public var asset: PHAsset!
    public var cellTappedAction: ((PHAsset) -> ()) = { _ in }

    var image: UIImage? {
        get { return imageView.image }
        set { imageView.image = newValue }
    }

    override init(frame: CGRect) {
      self.imageView = UIImageView()
      super.init(frame: frame)
        self.imageView.image = self.image
        self.imageView.frame = self.frame
        self.addSubview(self.imageView)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
//        fatalError("init(coder:) has not been implemented")
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        self.imageView.image = nil
    }
}

Controller: 控制器:

self.collectionView?.register(PhotosCollectionViewCell.self, forCellWithReuseIdentifier: "Cell")

So the first picture without IBOutlet and the second one with it 所以第一张图片没有IBOutlet,第二张图片没有IBOutlet

非情节提要单元 故事板单元

Register your class in viewDidLoad() viewDidLoad()注册您的课程

collectionView.register(PhotosCollectionViewCell.self, forCellReuseIdentifier: "photosCell")

Dequeue your cell in cellForItem and configure cell's subviews cellForItem单元出cellForItem并配置单元的子视图

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photosCell", for: indexPath)
// configure cell subviews

Remember to init your subview in PhotosCollectionViewCell as you won't be using IBOulets 记住要在PhotosCollectionViewCell初始化子视图,因为您将不会使用IBOulets

override init(frame: CGRect) {
    super.init(frame: frame)
    imageView.frame = contentView.bounds
    self.contentView.addSubview(imageView)
}

If you are trying to initialize your cell class with a certain image you should be able to do so by overriding the init method 如果您尝试使用某个图像初始化单元格类,则应该可以通过覆盖init方法来实现

override init(frame: CGRect) {
    super.init(frame: frame)
    //set initial image here
}

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

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