How to init collection view Cell with image without Storyboard or nib ?
I'm building ImagePicker and want to do it without storyboards
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:
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
Register your class in viewDidLoad()
collectionView.register(PhotosCollectionViewCell.self, forCellReuseIdentifier: "photosCell")
Dequeue your cell in cellForItem
and configure cell's subviews
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
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
override init(frame: CGRect) {
super.init(frame: frame)
//set initial image here
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.