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

In IOS how to implement (EULA) when app start first time
How to wait for finish dataTaskWithRequest?
Sequencing sounds with a delay in Swift
iOS 9 searchBar disappears from table header view when UISearchController is active
MFMessageComposeViewController not returning to application after send message ios9
This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes.
Writing a flood-fill method in Swift
Facebook Graph API query for latest album from page
Options for sending data to server/retrying requests in background
xcode, ios, Help Image Freezes, Not Moving
Hidden property cannot be changed within an animation block
MPmoviePlayer going black after updating to IOS 9 ( swift )
Run custom script after iOS app is signed in XCode
Video frames fill only 1/4 of the view - GL
How can I change the image in the detail view to access the master view
Can I use swift 1.2 with iOS 9? [closed]

Categories

HOME
html5-canvas
wpf
lua
xaml
path
jsonschema
wxpython
genetic-algorithm
stripe-payments
jasypt
netbeans-8
google-analytics-api
apple-mail
apache-spark-sql
tcplistener
bluej
w3.css
reload
resolve
numericupdown
org-mode
orientdb-2.1
servlet-filters
teamcity-9.0
spring-restdocs
atg
azure-ad-graph-api
broker
ssms-2014
wso2cep
jsgrid
mathdotnet
sql-server-2014-express
stl
magento2.0.2
toastr
tensor
sieve-of-eratosthenes
macvim
nio
google-slides
freerdp
program-slicing
dependency-management
website-hosting
android-gps
ganglia
replaygain
tpl-dataflow
masm32
liclipse
assembly-references
tastypie
rails-console
jasny-bootstrap
winobjc
accounts
storage-duration
java-gstreamer
xirr
json4s
gem
lossless-compression
short
b2b
declspec
execcommand
vlfeat
llblgenpro
programmers-notepad
arbtt
html5-apps
layout-manager
cloud-hosting
eject
ariatemplates
onmouseout
harvest
arden-syntax
vim-fugitive
media-manager
obout
closest
syncml
symstore
mkmapviewdelegate
network-scan
coords
server.transfer
nhaml
mud
ants

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