Cells not appearing in UICollectionView - swift

I don't understand why my cells aren't showing:
class MenuBar: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
let cellId = "pouet"
lazy var customCollectionView : UICollectionView = {
let layout = UICollectionViewLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = UIColor.gray
cv.dataSource = self
cv.delegate = self
return cv
}()
override init(frame: CGRect) {
super.init(frame: frame)
customCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
addSubview(customCollectionView)
addConstraintsWithFormat(format: "H:|[v0]|", views: customCollectionView)
addConstraintsWithFormat(format: "V:|[v0]|", views: customCollectionView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = customCollectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
print("test")
return cell
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Now my print("test") is not showing either, meaning that the method is actually not called, right? So what is wrong ?

Change this line of code:
let layout = UICollectionViewLayout()
To:
let layout = UICollectionViewFlowLayout()
UICollectionViewLayout is abstract class you can't use it directly.

Related

Setting imageView.image causes unbounded memory growth

Steps
Create UIImages in array
Load UIImage into reusable collection view cell
Scroll
View memory XCode
Code that repros the issue
import UIKit
class Cell: UICollectionViewCell {
static let ReuseIdentifier = "reuseID"
var imageView: UIImageView
override init(frame: CGRect) {
imageView = UIImageView()
super.init(frame: frame)
addSubview(imageView)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
imageView.frame = bounds
super.layoutSubviews()
}
func configureWith(image: UIImage) {
imageView.image = image
layoutSubviews()
}
}
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var images:[UIImage] = []
var collectionView: UICollectionView
required init?(coder: NSCoder) {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.register(Cell.self, forCellWithReuseIdentifier: Cell.ReuseIdentifier)
super.init(coder: coder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(collectionView)
collectionView.frame = view.frame
collectionView.backgroundColor = .green
collectionView.dataSource = self
collectionView.delegate = self
loadMoreImages()
collectionView.reloadData()
}
func loadMoreImages() {
for _ in 0...50 {
images.append(cloneImage(image: UIImage(named: "bigImage")!))
}
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(images.count)
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Cell.ReuseIdentifier, for: indexPath) as! Cell
cell.configureWith(image: images[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return view.frame.size
}
}
func cloneImage(image:UIImage) -> UIImage {
let newCgIm = image.cgImage!.copy()!
let newImage = UIImage(cgImage: newCgIm, scale: image.scale, orientation: image.imageOrientation)
return newImage
}
Video demo: https://i.stack.imgur.com/QRDWl.gif
Things that resolve the issue
Make UIImages optional, and set UIImages to nil after they've been displayed
Comment out imageView.image = image
Not using cloneImage, and instead images.append(UIImage(named: "bigImage")!)
Any idea what UIImageView is doing under the hood that causes unbounded memory growth? Seems like it's allocating a bunch of memory in the UIImage object that never gets released.

Label, font programmatically

I need help in this view.
I have to solve these things:
- instead of the 2 "duck" labels, I need to have different label.text with different fonts. I used this method here, in which I assign all the fonts to my datasource and assign the label to it by changing the font. the final result must be, for example, "duck" "ciccio" and "another"..
At the moment the view in which to insert the text is not connected to the colors or the fonts, I have to be able to insert the text and then if I click on a color it automatically changes the color to the written text and so the same thing for the fonts ..
What do I have to do?
I am attaching part of the code, only the one in which I put the "duck" label and the controller of the whole view.
that I have now
class CollectionFont: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
weak var delegate: FontDelegate?
var collectionView: UICollectionView?
let cellSpacing:CGFloat = 1
let indexPath: IndexPath
var datasource: [UIFont] = []
var imageArray: Array<UIImageView> = []
var onceOnly = false
init(datasource: [UIFont], index: IndexPath = [0,0]) {
self.indexPath = index
self.datasource = Theme.CustomFontsFamily.customFonts
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.delegate = self
collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewLayout())
collectionView!.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(collectionView!)
collectionView!.activate(constraint(edgesTo: self.view))
collectionView!.backgroundColor = Theme.Colors.sky
let collectionViewFlowLayout = UICollectionViewFlowLayout()
collectionView!.setCollectionViewLayout(collectionViewFlowLayout, animated: true)
collectionViewFlowLayout.scrollDirection = .horizontal
collectionViewFlowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
collectionViewFlowLayout.minimumLineSpacing = 0
collectionViewFlowLayout.minimumInteritemSpacing = 0
collectionView!.register(FontCell.self, forCellWithReuseIdentifier: FontCell.reuseIdentifier)
collectionView!.delegate = self
collectionView!.dataSource = self
collectionView!.isPagingEnabled = true
collectionView!.bounces = false
self.collectionView?.reloadData()
}
class FontRound {
let font: UILabel
init(font: UILabel) {
self.font = font
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
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: FontCell.reuseIdentifier, for: indexPath) as! FontCell
cell.array.font = self.datasource[indexPath.row]
return cell
}
//UICollectionViewDelegateFlowLayout - constraint della collecion view da innestare
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIScreen.main.bounds.size.width/4
let height = UIScreen.main.bounds.size.width/4
return CGSize(width: width, height: height)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
debugPrint("sucaaaa")
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
var visibleRect = CGRect()
visibleRect.origin = collectionView!.contentOffset
visibleRect.size = collectionView!.bounds.size
let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
guard let indexPath = collectionView!.indexPathForItem(at: visiblePoint) else { return }
print(indexPath[1])
self.delegate?.sincronizeScroll(indexPath: indexPath)
}
internal func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if !onceOnly {
//set the row and section you need.
collectionView.scrollToItem(at: self.indexPath, at: UICollectionView.ScrollPosition.right, animated: false)
onceOnly = true
}
}
}
final class CollectionFontView: UICollectionView {
init(_ collectionViewLayout: UICollectionViewLayout) {
super.init(frame: .zero, collectionViewLayout: collectionViewLayout)
self.backgroundColor = UIColor.red
self.showsHorizontalScrollIndicator = false
register(FontCell.self, forCellWithReuseIdentifier: FontCell.reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class FontCell: UICollectionViewCell {
static let reuseIdentifier = "FontCell_RID"
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
var cellID: String?
var array = UILabel().then{
$0.text = "duck"
$0.font = UIFont(name:"Jellee-Roman",size:15)
$0.contentMode = UIView.ContentMode.scaleAspectFit
$0.layer.cornerRadius = (((UIScreen.main.bounds.size.width/8)*0.8)/2)
}
func setupViews(){
self.addSubview(self.array)
self.array.activate([
array.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.8),
array.heightAnchor.constraint(equalTo: self.array.widthAnchor),
array.centerXAnchor.constraint(equalTo: self.centerXAnchor),
array.centerYAnchor.constraint(equalTo: self.centerYAnchor),
])
}
func setContents(container: UILabel) {
for sv in self.contentView.subviews {
sv.removeFromSuperview()
}
self.contentView.addSubview(container)
container.activate(constraint(edgesTo: self.contentView))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

uicollectionviewcells not showing [duplicate]

I have got this Swift code
`
let cellId="cellId"
class FeedController: UICollectionViewController{
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Centill"
collectionView?.reloadData()
collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath);
cell.backgroundColor = .yellow
return cell
}
}
class FeedCell: UICollectionViewCell {
override init(frame: CGRect){
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupViews(){
backgroundColor = .yellow
}
}
`
But unfortunately my cells are not showing.It only shows navigation bar and background color.what may be the problem with my code?
Try This code:
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 60, height: 60)
let myCollectionView:UICollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
myCollectionView.dataSource = self
myCollectionView.delegate = self
myCollectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
myCollectionView.backgroundColor = UIColor.whiteColor()
self.view.addSubview(myCollectionView)
You have to provide the size for collection view cell. add the below code snippet
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// calculate and return the height
}
In your cellForItemAt dataSource method you need to give custom UICollectionCell Class
let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! FeedCell
cell.backgroundColor = .yellow
return cell
Then you will able to see cell.
Try it.
You add in the class
UICollectionViewDataSource and UICollectionVIewDelegate.

Swift collectionViewCells are not showing

I have got this Swift code
`
let cellId="cellId"
class FeedController: UICollectionViewController{
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Centill"
collectionView?.reloadData()
collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath);
cell.backgroundColor = .yellow
return cell
}
}
class FeedCell: UICollectionViewCell {
override init(frame: CGRect){
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupViews(){
backgroundColor = .yellow
}
}
`
But unfortunately my cells are not showing.It only shows navigation bar and background color.what may be the problem with my code?
Try This code:
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 60, height: 60)
let myCollectionView:UICollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
myCollectionView.dataSource = self
myCollectionView.delegate = self
myCollectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
myCollectionView.backgroundColor = UIColor.whiteColor()
self.view.addSubview(myCollectionView)
You have to provide the size for collection view cell. add the below code snippet
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// calculate and return the height
}
In your cellForItemAt dataSource method you need to give custom UICollectionCell Class
let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! FeedCell
cell.backgroundColor = .yellow
return cell
Then you will able to see cell.
Try it.
You add in the class
UICollectionViewDataSource and UICollectionVIewDelegate.

Adding WebView to CollectionView without using MainStoryboard

I've been working on CollectionView with ImageView in each cells. Now I'm wondering how to add WebView working the same way as ImageView. I want it working as an element in each cell, is it possible? In addition, I am not using storyboard.
import UIKit
class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Home"
collectionView?.backgroundColor = UIColor.white
collectionView?.register(WebCell.self, forCellWithReuseIdentifier: "cellId")
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: view.frame.height - 500)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
class WebCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
let StronaSzkolna: UIImageView = {
let webview = UIImageView()
webview.backgroundColor = UIColor.blue
webview.translatesAutoresizingMaskIntoConstraints = false
return webview
}()
func setupViews() {
addSubview(StronaSzkolna)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]-16-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":StronaSzkolna]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-16-[v0]-16-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":StronaSzkolna]))
StronaSzkolna.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}