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

This certificate has an invalid issuer Apple Push Services
How to handle sessions with QuickBlox in iOS
getting nil value while calling api (alamofire)
iOS Convert m4a to amr before uploading
UIWebView fast scrolling to show large image lead to memory warning crash
Changing User Email and Password with Swift and Firebase
is there a clear understanding of IQWidgets library
Change constraint second item
Safari won't wait for user for Google sign-in redirect to iOS application
Swift - Download a video from distant URL and save it in an photo album
Declaration for an UIImage in NSObject
SequenceType with DictionaryGenerator - issues with Struct when Class works fine?
How to use object in whole class?
One tabBarItem draws two images occasionally
Show Default pop up for accessing the Twitter Account of the user
library not found for -lz for architecture armv7?

Categories

HOME
regex
whatsapp
gwt
vr
haskell-stack
fonts
genetic-algorithm
jqgrid
intel-xdk
sony
coded-ui-tests
intl
windows-10-desktop
xorg
pouchdb
tapi
facebook-opengraph
android-dialogfragment
drupal-commerce
cmusphinx
h.264
rational
snort
exe4j
hp-alm
jruby
ghost-blog
ibm-datapower
mouseevent
sax
listbox
fat-free-framework
ucwa
matterjs
apache-commons-httpclient
jtapi
pymssql
nav
outlook-vba
ecdsa
rights-management
plasticscm
nexus-5
tabview
syncfusion
hostname
phasset
website-hosting
jquery-masonry
derbyjs
sshd
assembly-references
setwindowshookex
post-increment
cglib
yapdatabase
wgs84
ssha
cng
hypervisor
heroku-toolbelt
abort
easynetq
alt
chatjs
mklink
symfony-2.5
bessel-functions
xacml3
hebrew
tlb
disabled-input
ducttape
ioerror
buildout
pubdate
sparc
nsmanagedobjectmodel
uptime
neventstore
slimbox
double-precision
symfony-2.2
cassette
xsocket
asp.net-session
hpple
openid4java
jammit
soapheader
system-tray
adbwireless
custom-protocol
sqlitemanager

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