![](/img/trans.png)
[英]How to init a UIViewController whose Nib is the Storyboard
[英]How to init collectionViewCell with image without Storyboard or nib?
如何在沒有Storyboard或筆尖的情況下初始化具有圖像的collection view Cell?
我正在構建ImagePicker,並且想要在沒有情節提要的情況下進行操作
所以帶有情節提要的工作代碼就是這樣,但是如何以編程方式進行呢?
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
}
}
我沒有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
}
}
控制器:
self.collectionView?.register(PhotosCollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
所以第一張圖片沒有IBOutlet,第二張圖片沒有IBOutlet
在viewDidLoad()
注冊您的課程
collectionView.register(PhotosCollectionViewCell.self, forCellReuseIdentifier: "photosCell")
在cellForItem
單元出cellForItem
並配置單元的子視圖
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photosCell", for: indexPath)
// configure cell subviews
記住要在PhotosCollectionViewCell
初始化子視圖,因為您將不會使用IBOulets
override init(frame: CGRect) {
super.init(frame: frame)
imageView.frame = contentView.bounds
self.contentView.addSubview(imageView)
}
如果您嘗試使用某個圖像初始化單元格類,則應該可以通過覆蓋init方法來實現
override init(frame: CGRect) {
super.init(frame: frame)
//set initial image here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.