ios


CollectionView - Release memory of UIImageViews from custom CollectionView Cells


I have a collectionView that I did programatically, in which I have four cell types and each contains an image.
I alternate this cells by the indexPath.item.
I want them to be released from memory when I pass through the cells in order to save memory.
With the current code the cell images are allocated in memory and are only released when I exit this ViewController, but I want them to be deallocated in the CollectionView.
I saw that it could be due to UIImage (named :) so I switched to UIImage (contentOfFile), but it continued in that way.
The closest I could do was to declare a global UIImageView and move to the cells, where inside each cell I save a weak var to this UIImageView, but the images do not appear and only the texts remain.
Would anyone know how I could free up the memory of each cell's images while the user scrolls the collectionview?
Bellow the code:
import UIKit
class Gallery_ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
lazy var galleryCollection: UICollectionView = {
let collectionLayout = UICollectionViewFlowLayout()
collectionLayout.scrollDirection = .horizontal
return UICollectionView(frame: .zero, collectionViewLayout: collectionLayout)
}()
var imageView = UIImageView()
let paths: [String] = [Bundle.main.path(forResource: “img1", ofType: "png", inDirectory: "Images")!,
Bundle.main.path(forResource: “img2", ofType: "png", inDirectory: "Images")!,
Bundle.main.path(forResource: “img3", ofType: "png", inDirectory: "Images")!,
Bundle.main.path(forResource: “img4”, ofType: "jpg", inDirectory: "Images")!]
// Called before showing the view
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
/// Setup
func setup() {
setup_views()
}
/// Setup views
func setup_views() {
galleryCollection.dataSource = self
galleryCollection.delegate = self
galleryCollection.isPagingEnabled = true
galleryCollection.showsHorizontalScrollIndicator = false
galleryCollection.register(Gallery_1_Cell.self, forCellWithReuseIdentifier: “GalleryCell_1")
galleryCollection.register(Gallery_2_Cell.self, forCellWithReuseIdentifier: “GalleryCell_2”)
galleryCollection.register(Gallery_3_Cell.self, forCellWithReuseIdentifier: “GalleryCell_3")
galleryCollection.register(Gallery_Final_Cell.self, forCellWithReuseIdentifier: “GalleryCell_Final")
view.addSubview(galleryCollection)
// apperance
galleryCollection.backgroundColor = .white
// constraints
galleryCollection.translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint(
item: galleryCollection, attribute: .centerX, relatedBy: .equal,
toItem: view, attribute: .centerX,
multiplier: 1,
constant: 0))
view.addConstraint(NSLayoutConstraint(
item: galleryCollection, attribute: .centerY, relatedBy: .equal,
toItem: view, attribute: .centerY,
multiplier: 1,
constant: 0))
view.addConstraint(NSLayoutConstraint(
item: galleryCollection, attribute: .width, relatedBy: .equal,
toItem: view, attribute: .width,
multiplier: 1,
constant: 0))
view.addConstraint(NSLayoutConstraint(
item: galleryCollection, attribute: .height, relatedBy: .equal,
toItem: view, attribute: .height,
multiplier: 1,
constant: 0))
}
// Returning Number of Cells
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
// Returning Cells
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print("Index: \(indexPath.item)")
print("Index Row: \(indexPath.row)")
//let imageV = UIImageView()
//imageView = imageV
if indexPath.item == 0 {
print("0000")
// creating cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GalleryCell_1", for: indexPath) as? Gallery_1_Cell
cell?.stringImagem = paths[indexPath.item]
cell?.imagem = UIImage(contentsOfFile: paths[indexPath.item])
cell?.backgroundImage = imageView
// passing collection view
//cell.backgroundImage = imageView
cell?.parentDelegate = self
// set custom apperance
cell?.setCustomApperance()
return cell!
}
if indexPath.item == 1 {
// creating cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GalleryCell_2”, for: indexPath) as? Gallery_2_Cell
print("1111")
cell?.stringImagem = paths[indexPath.item]
cell?.imagem = UIImage(contentsOfFile: paths[indexPath.item])
cell?.backgroundImage = imageView
// passing collection view
//cell.backgroundImage = imageView
cell?.parentDelegate = self
// set custom apperance
cell?.setCustomApperance()
return cell!
}
if indexPath.item == 2 {
// creating cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GalleryCell_3”, for: indexPath) as? Gallery_3_Cell
print("2222")
cell?.stringImagem = paths[indexPath.item]
cell?.imagem = UIImage(contentsOfFile: paths[indexPath.item])
cell?.backgroundImage = imageView
// passing collection view
cell?.parentDelegate = self
// set custom apperance
cell?.setCustomApperance()
return cell!
}
if indexPath.item == 3 {
// creating cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GalleryCell_Final", for: indexPath) as? Gallery_Final_Cell
print("3333")
cell?.stringImagem = paths[indexPath.item]
cell?.imagem = UIImage(contentsOfFile: paths[indexPath.item])
cell?.backgroundImage = imageView
// pass delegate
//cell.backgroundImage = imageView
cell?.parentDelegate = self
// set custom apperance
cell?.setCustomApperance()
return cell!
}
return UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
}
// Returning Cells Size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: view.frame.height)
}
// Setting the Space between lines
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
// Setting the Inter Space between lines
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
Below is the cell model I use, it's pretty much the same in the four cases, so I'll only put one.
import UIKit
class Gallery_1_Cell: UICollectionViewCell
{
// views
var backgroundImage: UIImageView?
weak var imagem : UIImage?
var stringImagem:String?
// Initializer
override init(frame: CGRect) {
super.init(frame: frame)
}
// Serializer
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
print("Cell1")
// self.subviews.forEach({ $0.removeFromSuperview() })
for v in self.subviews{
print("Cell1 Removeu")
print("V: \(v)")
v.removeFromSuperview()
}
}
/// Setup
func setup() {
setup_views()
setup_proportionalFonts()
}
/// Setup views
func setup_views() {
// Main View
self.clipsToBounds = true
// Background Image
let im = UIImage(contentsOfFile: stringImagem!)
backgroundImage?.image = im
self.addSubview(backgroundImage!)
// apperance
backgroundImage?.contentMode = .scaleAspectFill
backgroundImage?.backgroundColor = .red
// constraints
backgroundImage?.translatesAutoresizingMaskIntoConstraints = false
self.addConstraint(NSLayoutConstraint(
item: backgroundImage!, attribute: .centerX, relatedBy: .equal,
toItem: self, attribute: .centerX,
multiplier: 1,
constant: 0))
self.addConstraint(NSLayoutConstraint(
item: backgroundImage!, attribute: .centerY, relatedBy: .equal,
toItem: self, attribute: .centerY,
multiplier: 1,
constant: 0))
self.addConstraint(NSLayoutConstraint(
item: backgroundImage!, attribute: .width, relatedBy: .equal,
toItem: self, attribute: .width,
multiplier: 1,
constant: 0))
self.addConstraint(NSLayoutConstraint(
item: backgroundImage!, attribute: .height, relatedBy: .equal,
toItem: self, attribute: .height,
multiplier: 1,
constant: 0))
/// Set Custom Apperance
func setCustomApperance() {
setup()
}
}

Related Links

Create a graph with a Midi File
swift3 present from appdelegate error : Warning: Attemp to present ~ whose view is not in the window hierarchy
Bottom Corners are not working in swift
Can't use Swift in WatchKit extension
How to access and store photo after calling capturePhoto(with:delegate:)
Passing JSON Response From HTTP Request to Another ViewController in Swift 3
CompletionHandler for Alamofire
iOS open sco tx please
Firebase Google Ads not Display after change package name
Firebase Swift equivalent of push()
When does network spinner appear? [duplicate]
Xamarin MainStoryBoard opening error: Object reference not set to an instance of an object
UIPanGestureRecognizer Fading View after a limit
How to run a function when tableviewcell is selected (for example, update UIImageView when cell is pressed)
Alamofire called twice - Swift
'AppDelegate' does not conform to protocol 'GIDSignInDelegate'

Categories

HOME
order
applet
design
application-cache
addeventlistener
wso2is
delphi-xe7
pyusb
regression
intl
hadoop2
superfish
research
proftpd
pouchdb
openmodelica
nservicebus
numericupdown
ellipse
message
drupal-commerce
jscodeshift
jmeter-plugins
spark-graphx
centroid
hough-transform
italic
angular-services
parallax
icloud-drive
effects
python-behave
scatter-plot
apache-commons-httpclient
tweenmax
rhel7
nav
zipline
packaging
perl-module
runc
amazon-elasticsearch
worldpay
php-5.5
angularjs-routing
mediawiki-api
botkit
gretl
strip-tags
adal.js
clientscript
ssms-2012
azure-cdn
formstack
tpl-dataflow
tastypie
mysql-error-1050
mysql-notifier
topojson
logstash-jdbc
qlpreviewcontroller
angularjs-filter
winobjc
rabbitvcs
highslide
balana
post-processor
cng
symbian
hypervisor
appv
kindlegen
devenv
boost-coroutine
alienvault
size-t
wintersmith
mkpolyline
wso2as
centering
scribe
jasmin
bitrock
sqlhelper
opensc
prettyfaces
ash
pkcs#10
xcode6.1.1
angularjs-google-maps
jxta
pydatalog
appstore-sandbox
onejar
emitmapper
mips64
emacs-jedi
repeating
jquery-data
nsmanagedobjectmodel
jflow
uptime
guice-servlet
northwind
layout-manager
wpf-4.0
objcopy
ondraw
nscollectionviewitem
alivepdf
n900
wmd
coords
geneva-framework
newsgroup

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App