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

how to animate setting rootViewController for window
Crash when accessing nested completion block — EXC_BAD_ACCESS
UIButton border color defaults to black. How can it be changed to the default ( blue ) color that is used for setting the title of the button text?
navigation bar hides on resturning back to search controller from another view controller
How to avoid text color to change on UIButton selection with selectors on UIControlEvents?
my table view is created but array is not showing in table view,in console all the data are coming.please help me to solve json parsing
Dropbox UIDocumentPicker plugin cannot open OS X file packages
How to use delegates properly in Swift?
swift stop 360 degree animation
Core Data App group synchronization (w/ extension)
iOS Bugsnag exception - EXC_BAD_ACCESS _dispatch_dispose Attempted to dereference garbage pointer
why my array is null in second time, when I assigned it's first object to dictionay in objective C, ios
Why text get line break when scroll
Writing text on pdf ios
How to achieve this layout on buttons and text fields in XCode using swift? [closed]
how to trim a video in swift for a particular time

Categories

HOME
apache-spark
xaml
feed
jasypt
freebsd
py.test
push
eps
vulkan
group-by
calabash-android
rgb
factory-girl
watchservice
embed
lazy-loading
lookup-tables
thrift
many-to-many
amazon-cloudfront
google-distancematrix-api
addthis
naturallyspeaking
italic
pdfa
android-security
asp.net-identity-2
dapper-fastcrud
angular2-databinding
lync
cloudinary
machine-language
spring-websocket
deep-copy
google-domain-api
powerbuilder-conversion
qweb
sourcetree
knowledge-management
backwards-compatibility
pci
freecodecamp
gulp-babel
default-browser
ewsjavaapi
requirements-management
clientscript
fido
zbar
jvm-arguments
ifc
gwt-material-design
ckcontainer
struts1
visual-build-professional
dms
rras
enhanced-ecommerce
jstorm
mongolab
lidar
strace
win32com
xsb
node-orm2
cbc-mode
react-rails
byte-order-mark
wintersmith
movie
antiforgerytoken
min3d
java-client
swift-array
tortoisecvs
mysql5
epoll
directcompute
zeroclipboard
custom-titlebar
jquery-backstretch
mydbr
jxta
jquery-mobile-popup
apache-commons-dbcp
zephir
virtual-earth
dependency-walker
rc-shell
mixing
graphiti-js
force.com
measure
jboss-cache
regexbuddy
seam-conversation
iphone-sdk-3.1
68hc11
clipboard-pictures
graceful-degradation

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