Crashing: Thread 1: EXC_BAD_ACCESS when I set custom cell imageView - ios

I tried a lot but I am not able to solve it. Following is the code that I have tried. Getting issue at
cell.userImageView.image = self.selectedPhotos[0] // Thread 1: EXC_BAD_ACCESS (code=2, address=0x1208e5520)
Line above are inside
func convertAssetsToImage(cell: UserProfilePhotosCell)
I use BSImagePicker to pick images from the gallery.
Here is the full code:
import UIKit
import BSImagePicker
import Photos
class UserProfileVC: BaseCollectionViewController {
// MARK: Properties
let userPhotoId = "userPhotoId"
var SelectedAssets = [PHAsset]()
var selectedPhotos = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = .white
collectionView.register(UserProfilePhotosCell.self, forCellWithReuseIdentifier: userPhotoId)
print("Did load once")
}
#objc func showCustomImagePicker(cell1: UserProfilePhotosCell) {
let imagePicker = ImagePickerController()
imagePicker.settings.selection.max = 1
imagePicker.settings.selection.unselectOnReachingMax = true
imagePicker.settings.fetch.assets.supportedMediaTypes = [.image]
imagePicker.albumButton.tintColor = UIColor.green
imagePicker.cancelButton.tintColor = UIColor.red
imagePicker.doneButton.tintColor = UIColor.purple
imagePicker.navigationBar.barTintColor = .black
imagePicker.settings.theme.backgroundColor = .black
imagePicker.settings.theme.selectionFillColor = UIColor.gray
imagePicker.settings.theme.selectionStrokeColor = UIColor.yellow
imagePicker.settings.theme.selectionShadowColor = UIColor.red
imagePicker.settings.theme.previewTitleAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16),NSAttributedString.Key.foregroundColor: UIColor.white]
imagePicker.settings.theme.previewSubtitleAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12),NSAttributedString.Key.foregroundColor: UIColor.white]
imagePicker.settings.theme.albumTitleAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18),NSAttributedString.Key.foregroundColor: UIColor.white]
imagePicker.settings.list.cellsPerRow = {(verticalSize: UIUserInterfaceSizeClass, horizontalSize: UIUserInterfaceSizeClass) -> Int in
switch (verticalSize, horizontalSize) {
case (.compact, .regular): // iPhone5-6 portrait
return 2
case (.compact, .compact): // iPhone5-6 landscape
return 2
case (.regular, .regular): // iPad portrait/landscape
return 3
default:
return 2
}
}
self.presentImagePicker(imagePicker, select: { (asset) in
print("Selected: \(asset)")
}, deselect: { (asset) in
print("Deselected: \(asset)")
}, cancel: { (assets) in
print("Canceled with selections: \(assets)")
}, finish: { (assets) in
print("Finished with selections: \(assets)")
print("Count of Assets: \(assets.count)")
self.SelectedAssets = assets
self.convertAssetsToImage(cell: cell1)
})
}
func convertAssetsToImage(cell: UserProfilePhotosCell) {
for asset in SelectedAssets {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.isSynchronous = true
manager.requestImage(for: asset, targetSize: CGSize(width: 340, height: 365), contentMode: .aspectFit, options: option, resultHandler: {(result, info) -> Void in
thumbnail = result!
})
self.selectedPhotos.append(thumbnail)
}
DispatchQueue.main.async {
cell.userImageView.image = self.selectedPhotos[0]
print("Dispatch")
}
}
}
extension UserProfileVC: UICollectionViewDelegateFlowLayout {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: userPhotoId, for: indexPath) as! UserProfilePhotosCell
cell.backgroundColor = .yellow
cell.userImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showCustomImagePicker(cell1:))))
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return .init(width: view.frame.width, height: 500)
}
}
Custom Cell Code:
import UIKit
import BSImagePicker
import Photos
class UserProfilePhotosCell: UICollectionViewCell {
var userImageView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "megan")
iv.contentMode = .scaleAspectFill
iv.layer.cornerRadius = 8
iv.clipsToBounds = true
iv.constrainHeight(constant: 200)
iv.backgroundColor = .red
iv.isUserInteractionEnabled = true
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
setupUI()
print("Did init once")
}
fileprivate func setupUI() {
addSubview(userImageView)
userImageView.topAnchor.constraint(equalTo: topAnchor).isActive = true
// userImageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
userImageView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
userImageView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
I have tried also to pass array with images to UserProfilePhotosCell, and update userImageView.image inside didSet method, no luck, same error.
Thank you in advance for any help.

Related

View controller isn't called when back from another view using tab bar

I have a simple application with two controllers, the navigation between which is carried out through the UITabBarController. When the application starts, everything works as it should, when it is initialized for the first time, but when I change something in the first VC and switch to second VC, and then try again to return to the first VC - it does not appear.
ViewWillAppear() addition didn't work in my case, because debugger didn’t even show that the ViewDidLoad() or ViewWillAppear() functions worked in the first VC.
Thats how its look (CloudApp record)
MainTabBarController code:
class MainTabBarController: UITabBarController {
var photosVC: PhotosCollectionViewController!
var likesVC: LikesCollectionViewController!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
photosVC = PhotosCollectionViewController(collectionViewLayout: WaterfallLayout())
likesVC = LikesCollectionViewController(collectionViewLayout: UICollectionViewFlowLayout())
viewControllers = [
generateNavigationController(rootViewController: photosVC, title: "Photos", image: #imageLiteral(resourceName: "photos")),
generateNavigationController(rootViewController: likesVC, title: "Favourites", image: #imageLiteral(resourceName: "heart"))
]
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
if (self.selectedViewController?.isKind(of: UINavigationController.self))!
{
let nav = self.selectedViewController as! UINavigationController
nav.popToRootViewController(animated: false)
}
}
private func generateNavigationController(rootViewController: UIViewController, title: String, image: UIImage) -> UIViewController {
let navigationVC = UINavigationController(rootViewController: rootViewController)
navigationVC.tabBarItem.title = title
navigationVC.tabBarItem.image = image
return navigationVC
}
}
PhotosCollectionVC code:
import UIKit
class PhotosCollectionViewController: UICollectionViewController {
var networkDataFetcher = NetworkDataFetcher()
private var timer: Timer?
private var photos = [UnsplashPhoto]()
private var selectedImages = [UIImage]()
// private let itemsPerRow: CGFloat = 2 // относится к UICollectionViewDelegateFlowLayout
// private let sectionInserts = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) // относится к UICollectionViewDelegateFlowLayout
private lazy var addBarButtonItem: UIBarButtonItem = {
return UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addBarButtonTapped))
}()
private lazy var actionBarButtonItem: UIBarButtonItem = {
return UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(actionBarButtonTapped))
}()
private var numberOfSelectedPhotos: Int {
return collectionView.indexPathsForSelectedItems?.count ?? 0
}
private let enterSearchTermLabel: UILabel = {
let label = UILabel()
label.text = "Please enter search term above..."
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 20)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let spinner: UIActivityIndicatorView = {
let spinner = UIActivityIndicatorView(style: .gray)
spinner.translatesAutoresizingMaskIntoConstraints = false
return spinner
}()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupNavigationBar()
setupCollectionView()
setupSearchBar()
setupEnterLabel()
setupSpinner()
}
private func undateNavButtonsState() {
addBarButtonItem.isEnabled = numberOfSelectedPhotos > 0
actionBarButtonItem.isEnabled = numberOfSelectedPhotos > 0
}
func refresh() {
self.selectedImages.removeAll()
self.collectionView.selectItem(at: nil, animated: true, scrollPosition: [])
undateNavButtonsState()
}
// MARK: - NavigationItems action
#objc private func addBarButtonTapped() {
print(#function)
let selectedPhotos = collectionView.indexPathsForSelectedItems?.reduce([], { (photosss, indexPath) -> [UnsplashPhoto] in
var mutablePhotos = photosss
let photo = photos[indexPath.item]
mutablePhotos.append(photo)
return mutablePhotos
})
let alertController = UIAlertController(title: "", message: "\(selectedPhotos!.count) фото будут добавлены в альбом", preferredStyle: .alert)
let add = UIAlertAction(title: "Добавить", style: .default) { (action) in
let tabbar = self.tabBarController as! MainTabBarController
let navVC = tabbar.viewControllers?[1] as! UINavigationController
let likesVC = navVC.topViewController as! LikesCollectionViewController
likesVC.photos.append(contentsOf: selectedPhotos ?? [])
likesVC.collectionView.reloadData()
self.refresh()
}
let cancel = UIAlertAction(title: "Отменить", style: .cancel) { (action) in
}
alertController.addAction(add)
alertController.addAction(cancel)
present(alertController, animated: true)
}
#objc private func actionBarButtonTapped(sender: UIBarButtonItem) {
print(#function)
let shareController = UIActivityViewController(activityItems: selectedImages, applicationActivities: nil)
shareController.completionWithItemsHandler = { _, bool, _, _ in
if bool {
self.refresh()
}
}
shareController.popoverPresentationController?.barButtonItem = sender
shareController.popoverPresentationController?.permittedArrowDirections = .any
present(shareController, animated: true, completion: nil)
}
// MARK: - Setup UI Elements
private func setupCollectionView() {
collectionView.backgroundColor = .white
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CellId")
collectionView.register(PhotosCell.self, forCellWithReuseIdentifier: PhotosCell.reuseId)
collectionView.layoutMargins = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
collectionView.contentInsetAdjustmentBehavior = .automatic
collectionView.allowsMultipleSelection = true
if let waterfallLayout = collectionViewLayout as? WaterfallLayout {
waterfallLayout.delegate = self
}
}
private func setupEnterLabel() {
collectionView.addSubview(enterSearchTermLabel)
enterSearchTermLabel.centerXAnchor.constraint(equalTo: collectionView.centerXAnchor).isActive = true
enterSearchTermLabel.topAnchor.constraint(equalTo: collectionView.topAnchor, constant: 50).isActive = true
}
private func setupSpinner() {
view.addSubview(spinner)
spinner.centerXAnchor.constraint(equalTo: collectionView.centerXAnchor).isActive = true
spinner.centerYAnchor.constraint(equalTo: collectionView.centerYAnchor).isActive = true
}
private func setupNavigationBar() {
let titleLabel = UILabel(text: "PHOTOS", font: .systemFont(ofSize: 15, weight: .medium), textColor: #colorLiteral(red: 0.5019607843, green: 0.4980392157, blue: 0.4980392157, alpha: 1))
navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: titleLabel)
navigationItem.rightBarButtonItems = [actionBarButtonItem, addBarButtonItem]
navigationController?.hidesBarsOnSwipe = true
actionBarButtonItem.isEnabled = false
addBarButtonItem.isEnabled = false
}
private func setupSearchBar() {
let seacrhController = UISearchController(searchResultsController: nil)
navigationItem.searchController = seacrhController
navigationItem.hidesSearchBarWhenScrolling = false
seacrhController.hidesNavigationBarDuringPresentation = false
seacrhController.obscuresBackgroundDuringPresentation = false
seacrhController.searchBar.delegate = self
}
// MARK: - UICollecionViewDataSource, UICollecionViewDelegate
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
enterSearchTermLabel.isHidden = photos.count != 0
return photos.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotosCell.reuseId, for: indexPath) as! PhotosCell
let unspashPhoto = photos[indexPath.item]
cell.unsplashPhoto = unspashPhoto
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
undateNavButtonsState()
let cell = collectionView.cellForItem(at: indexPath) as! PhotosCell
guard let image = cell.photoImageView.image else { return }
selectedImages.append(image)
}
override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
undateNavButtonsState()
let cell = collectionView.cellForItem(at: indexPath) as! PhotosCell
guard let image = cell.photoImageView.image else { return }
if let index = selectedImages.firstIndex(of: image) {
selectedImages.remove(at: index)
}
}
}
// MARK: - UISearchBarDelegate
extension PhotosCollectionViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
print(searchText)
self.spinner.startAnimating()
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: { (_) in
self.networkDataFetcher.fetchImages(searchTerm: searchText) { [weak self] (searchResults) in
guard let fetchedPhotos = searchResults else { return }
self?.spinner.stopAnimating()
self?.photos = fetchedPhotos.results
self?.collectionView.reloadData()
self?.refresh()
}
})
}
}
// MARK: - WaterfallLayoutDelegate
extension PhotosCollectionViewController: WaterfallLayoutDelegate {
func waterfallLayout(_ layout: WaterfallLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let photo = photos[indexPath.item]
return CGSize(width: photo.width, height: photo.height)
}
}
LikesCollectionVC code:
import UIKit
class LikesCollectionViewController: UICollectionViewController {
var photos = [UnsplashPhoto]()
private lazy var trashBarButtonItem: UIBarButtonItem = {
return UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: nil)
}()
private let enterSearchTermLabel: UILabel = {
let label = UILabel()
label.text = "You haven't add a photos yet"
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 20)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = .white
collectionView.register(LikesCollectionViewCell.self, forCellWithReuseIdentifier: LikesCollectionViewCell.reuseId)
collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.minimumInteritemSpacing = 1
layout.minimumLineSpacing = 1
setupEnterLabel()
setupNavigationBar()
}
// MARK: - Setup UI Elements
private func setupEnterLabel() {
collectionView.addSubview(enterSearchTermLabel)
enterSearchTermLabel.centerXAnchor.constraint(equalTo: collectionView.centerXAnchor).isActive = true
enterSearchTermLabel.topAnchor.constraint(equalTo: collectionView.topAnchor, constant: 50).isActive = true
}
private func setupNavigationBar() {
let titleLabel = UILabel(text: "FAVOURITES", font: .systemFont(ofSize: 15, weight: .medium), textColor: #colorLiteral(red: 0.5, green: 0.5, blue: 0.5, alpha: 1))
navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: titleLabel)
navigationItem.rightBarButtonItem = trashBarButtonItem
trashBarButtonItem.isEnabled = false
}
// MARK: - UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
enterSearchTermLabel.isHidden = photos.count != 0
return photos.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: LikesCollectionViewCell.reuseId, for: indexPath) as! LikesCollectionViewCell
let unsplashPhoto = photos[indexPath.item]
cell.unsplashPhoto = unsplashPhoto
return cell
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension LikesCollectionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.frame.width
return CGSize(width: width/3 - 1, height: width/3 - 1)
}
}
the navigation between which is carried out through the UITabBarController.
No, that is not what you are doing. Your tab bar controller does not navigate between your two view controllers. It navigates between two navigation controllers.
And that’s the problem. You cannot detect anything in viewDidAppear because your view controller is not what appears when the tab controller switches. What appears is the navigation controller.

Function not triggering on scroll

I am trying to trigger a certain function in a collection view when I scroll. Basically Im trying to implement pagination so that when it scrolls to the bottom more items are loaded.
override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.item >= allEvents.count - 1 {
// print("paginating for post")
paginationHelper.paginate(completion: { [unowned self] (events) in
self.allEvents.append(contentsOf: events)
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
})
}else{
print("Not paginating")
}
}
This is the entire Function
import Foundation
import UIKit
import Alamofire
import AlamofireNetworkActivityIndicator
import SwiftLocation
import CoreLocation
import AMScrollingNavbar
class HomeFeedController: UICollectionViewController, UICollectionViewDelegateFlowLayout,UIGestureRecognizerDelegate {
// let dropDownLauncher = DropDownLauncher()
var isFinishedPaging = false
let detailView = EventDetailViewController()
let refreshControl = UIRefreshControl()
var emptyLabel: UILabel?
var allEvents = [Event]()
//will containt array of event keys
var eventKeys = [String]()
let customCellIdentifier = "customCellIdentifier"
var grideLayout = GridLayout(numberOfColumns: 2)
lazy var dropDownLauncer : DropDownLauncher = {
let launcer = DropDownLauncher()
launcer.homeFeed = self
return launcer
}()
let paginationHelper = PaginationHelper<Event>(serviceMethod: PostService.showEvent)
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = UIColor.white
collectionView?.collectionViewLayout = grideLayout
collectionView?.reloadData()
self.collectionView?.contentInset = UIEdgeInsetsMake(15, 0, 0, 0)
navigationItem.title = "Home"
collectionView?.register(CustomCell.self, forCellWithReuseIdentifier: customCellIdentifier)
// self.navigationItem.hidesBackButton = true
let backButton = UIBarButtonItem(image: UIImage(named: "menu"), style: .plain, target: self, action: #selector(handleDropDownMenu))
self.navigationItem.leftBarButtonItem = backButton
// PostService.showEvent(location: User.current.location!) { (event) in
// self.allEvents = event
// print(self.allEvents)
//
// DispatchQueue.main.async {
// self.collectionView?.reloadData()
// }
// }
configureCollectionView()
reloadHomeFeed()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let navigationController = self.navigationController as? ScrollingNavigationController {
navigationController.followScrollView(self.collectionView!, delay: 50.0)
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if let navigationController = navigationController as? ScrollingNavigationController {
navigationController.stopFollowingScrollView()
}
}
override func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
if let navigationController = navigationController as? ScrollingNavigationController {
navigationController.showNavbar(animated: true)
}
return true
}
func handleDropDownMenu(){
dropDownLauncer.showDropDown()
}
//will query by selected category
func categoryFetch(dropDown: DropDown){
navigationItem.title = dropDown.name
paginationHelper.category = dropDown.name
configureCollectionView()
reloadHomeFeed()
}
func reloadHomeFeed() {
self.paginationHelper.reloadData(completion: { [unowned self] (events) in
self.allEvents = events
if self.refreshControl.isRefreshing {
self.refreshControl.endRefreshing()
}
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
})
}
func configureCollectionView() {
// add pull to refresh
refreshControl.addTarget(self, action: #selector(reloadHomeFeed), for: .valueChanged)
collectionView?.addSubview(refreshControl)
}
// need to tell it how many cells to have
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return allEvents.count
}
// need to tell the collection view controller what type of cell we want to return
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let customCell = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath) as! CustomCell
let imageURL = URL(string: allEvents[indexPath.item].currentEventImage)
print(imageURL ?? "")
customCell.sampleImage.af_setImage(withURL: imageURL!)
return customCell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//let selectedEvent = self.imageArray[indexPath.row]
//let eventDetailVC
if let cell = collectionView.cellForItem(at: indexPath){
// print("Look here for event name")
// print(detailView.eventName)
detailView.eventKey = allEvents[indexPath.row].key!
detailView.eventPromo = allEvents[indexPath.row].currentEventPromo!
detailView.currentEvent = allEvents[indexPath.row]
present(detailView, animated: true, completion: nil)
//self.navigationController?.pushViewController(detailView, animated: true)
}
print("Cell \(indexPath.row) selected")
}
override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.item >= allEvents.count - 1 {
// print("paginating for post")
paginationHelper.paginate(completion: { [unowned self] (events) in
self.allEvents.append(contentsOf: events)
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
})
}else{
print("Not paginating")
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
//will make surepictures keep same orientation even if you flip screen
// will most likely lock into portrait mode but still good to have
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
grideLayout.invalidateLayout()
}
//Will allow the first two cells that are displayed to be of varying widths
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.item == 0 || indexPath.item == 1 {
return CGSize(width: view.frame.width, height: grideLayout.itemSize.height)
}else{
return grideLayout.itemSize
}
}
func showLeftView(sender: AnyObject?){
print("Button Pressed")
// sideMenuController?.leftViewController = LeftViewController()
//sideMenuController?.showLeftView(animated: true, completionHandler: nil)
}
}
//responsible for populating each cell with content
class CustomCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
let sampleImage: UIImageView = {
let firstImage = UIImageView()
firstImage.clipsToBounds = true
firstImage.translatesAutoresizingMaskIntoConstraints = false
firstImage.contentMode = .scaleToFill
firstImage.layer.masksToBounds = true
return firstImage
}()
let nameLabel: UILabel = {
let name = UILabel()
name.text = "Custom Text"
name.translatesAutoresizingMaskIntoConstraints = false
return name
}()
func setupViews() {
addSubview(sampleImage)
backgroundColor = UIColor.white
//addSubview(nameLabel)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": sampleImage]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": sampleImage]))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// responsible for creating the grid layout that you see in the home view feed
class GridLayout: UICollectionViewFlowLayout {
var numberOfColumns:Int = 2
init(numberOfColumns: Int) {
super.init()
// controlls spacing inbetween them as well as spacing below them to next item
self.numberOfColumns = numberOfColumns
self.minimumInteritemSpacing = 3
self.minimumLineSpacing = 5
}
// just needs to be here because swift tells us to
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var itemSize: CGSize{
get{
if collectionView != nil {
let collectionVieweWidth = collectionView?.frame.width
let itemWidth = (collectionVieweWidth!/CGFloat(self.numberOfColumns)) - self.minimumInteritemSpacing
let itemHeight: CGFloat = 200
return CGSize(width: itemWidth, height: itemHeight)
}
return CGSize(width: 100, height: 100)
}set{
super.itemSize = newValue
}
}
}
This is the function that is responsible for triggering the event but it seems to go to the else statement literally every time. Any insight would be helpful

CollectionView infinite scroll in Swift with Json parse

I wrote the code for collectionView infinite scroll with json parse. Next want to view 20 data each time. After print 20data i will show footer.
Now it is going to view all data in a time. Json parse is ok, also footer view is ok. But the problem is infinite-scroll is not working at all.
Here is my all code:
import Foundation
import UIKit
enum LoadMoreStatus{
case loading
case finished
case haveMore
}
class Product: NSObject {
var id: Int?
var category_id: Int?
var image: String?
var name: String?
var ar_name: String?
var ar_description: String?
var price: NSNumber?
var quantity: String?
var is_featured: String?
var seller_id: String?
var payment_required: String?
var is_editors_choice: String?
var created_at: String?
var updated_at: String?
}
let categoryCellid = "categoryCellid"
class ProductByCategoryCollectionView: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var headercellId = "headercellId"
var footerCellid = "firstfootercellid"
var numberOfCells = 5
var loadingStatus = LoadMoreStatus.haveMore
var arrProduct = [Product]()
var category_id:Int = 0;
var product_count:Int = 0;
func reloadData(){
collectionView?.reloadData()
if numberOfCells > 0 {
collectionView?.scrollToItem(at: IndexPath(row: 0, section: 0), at: .left, animated: true)
}
}
func loadMore() {
if numberOfCells >= arrProduct.count{ // here will show untill 22
loadingStatus = .finished
collectionView?.reloadData()
return
}
Timer.schedule(delay: 2) { timer in
self.numberOfCells += 10
self.collectionView?.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.getPropductListByCategory()
collectionView?.backgroundColor = .white
navigationItem.title = "Product"
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil)
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Sort By", style: .plain, target: nil, action: nil)
self.setupHeaderView()
collectionView?.register(ProductByCategoryCollectionViewCell.self, forCellWithReuseIdentifier: categoryCellid)
collectionView?.register(ProductByCategoryFooterCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: footerCellid)
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
var text=""
switch UIDevice.current.orientation{
case .portrait:
text="Portrait"
case .portraitUpsideDown:
text="PortraitUpsideDown"
case .landscapeLeft:
text="LandscapeLeft"
case .landscapeRight:
text="LandscapeRight"
default:
text="Another"
}
NSLog("You have moved: \(text)")
collectionView?.reloadData()
}
func showCategoryDetailSegue() {
let detailcontroller = UIViewController()
navigationController?.pushViewController(detailcontroller, animated: true)
}
func sortBtnTarget() {
}
func filterBtnTarget() {
}
let dividedLine: UIView = {
let view = UIView()
view.backgroundColor = UIColor(white: 0.4, alpha: 0.4)
return view
}()
let totalItemLabel: UILabel = {
let label = UILabel()
label.text = ""
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 15)
label.backgroundColor = UIColor.white
return label
}()
let dividerLineView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.white
return view
}()
func setupHeaderView(){
view.backgroundColor = UIColor(white: 0.4, alpha: 0.4)
dividedLine.frame = CGRect(x: 0, y: 95, width: view.frame.width, height: 1)
totalItemLabel.frame = CGRect(x: 0, y: 55, width: view.frame.width, height: 40)
view.addSubview(totalItemLabel)
view.addSubview(dividedLine)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrProduct.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if(indexPath.row==arrProduct.count-1){
if loadingStatus == .haveMore {
self.perform(#selector(ProductByCategoryCollectionView.loadMore), with: nil, afterDelay: 0)
}
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: categoryCellid, for: indexPath) as! ProductByCategoryCollectionViewCell
cell.callProductObject4Cell = arrProduct[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 172, height: 300)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(32, 10, 0, 10)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let controller1 = UICollectionViewController(collectionViewLayout: layout)
navigationController?.pushViewController(controller1, animated: true)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
collectionView?.collectionViewLayout.invalidateLayout()
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
var footerView:ProductByCategoryFooterCell!
if (kind == UICollectionElementKindSectionFooter) && (loadingStatus != .finished){
footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: footerCellid, for: indexPath) as! ProductByCategoryFooterCell
}
return footerView
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return (loadingStatus == .finished) ? CGSize.zero : CGSize(width: self.view.frame.width, height: 50)
}
}
class ProductByCategoryCollectionViewCell: UICollectionViewCell {
var callProductObject4Cell: Product?{
didSet {
productLabel.text = callProductObject4Cell?.name
if let price = callProductObject4Cell?.price {
//priceLabel.text = "$\(price)"
priceLabel.text = "\(price) TK"
} else {
priceLabel.text = ""
}
if let profileImageUrl = callProductObject4Cell?.image {
productImage.loadImageUsingUrlString(profileImageUrl)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupcategoryCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let productImage: UIImageView = {
let image = UIImageView()
image.image = UIImage(named: "default")
image.contentMode = .scaleAspectFit
image.layer.borderWidth = 1
image.layer.borderColor = UIColor.orange.cgColor
image.layer.masksToBounds = true
return image
}()
let productLabel: UILabel = {
let label = UILabel()
label.text = "productName"
label.textColor = .black
label.numberOfLines = 0
label.font = UIFont.boldSystemFont(ofSize: 10)
return label
}()
let priceLabel: UILabel = {
let label = UILabel()
// label.backgroundColor = .lightGray
label.text = ""
label.textColor = .orange
label.font = UIFont.systemFont(ofSize: 13)
return label
}()
func setupcategoryCell() {
addSubview(productImage)
addSubview(productLabel)
addSubview(priceLabel)
addConstraintsWithFormat("H:|[v0]|", views: productImage)
addConstraintsWithFormat("V:|[v0(230)]-2-[v1][v2(10)]-5-|", views: productImage,productLabel, priceLabel)
addConstraintsWithFormat("H:|[v0]|", views: productLabel)
addConstraintsWithFormat("H:|[v0]|", views: priceLabel)
}
}
class ProductByCategoryFooterCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
setupCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let menuHeaderLabel: UILabel = {
let label = UILabel()
label.text = "loadin more waiting"
label.textColor = .green
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 15)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
func setupCell() {
addSubview(menuHeaderLabel)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-8-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": menuHeaderLabel]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-5-[v0(30)]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": menuHeaderLabel]))
}
}
extension Timer {
class func schedule(delay: TimeInterval, handler: #escaping (Timer!) -> Void) -> Timer {
let fireDate = delay + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
return timer!
}
class func schedule(repeatInterval interval: TimeInterval, handler: #escaping (Timer!) -> Void) -> Timer {
let fireDate = interval + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
return timer!
}
}
enum LoadMoreStatus {
case loading
case finished
case haveMore
}
class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var verticalDataSource = [String]()
var firstCellid = "firstcellid"
var firstFooterCellid = "firstfootercellid"
var numberOfCells = 5
var loadingStatus = LoadMoreStatus.haveMore
func reloadData() {
//numberOfCells = 10
collectionView?.reloadData()
if numberOfCells > 0 {
collectionView?.scrollToItem(at: IndexPath(row: 0, section: 0), at: .left, animated: true)
}
}
func loadMore() {
if numberOfCells >= 40 {
// here will show untill finished number
loadingStatus = .finished
collectionView?.reloadData()
return
}
// Replace code with web service and append to data source
Timer.schedule(delay: 2) { timer in
self.numberOfCells += 2
self.collectionView?.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
collectionView?.register(VerticalCollectionViewCell.self, forCellWithReuseIdentifier: firstCellid)
collectionView?.register(VerticalCollectionViewCell2.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: firstFooterCellid)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK - Rotation methods
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
var text=""
switch UIDevice.current.orientation {
case .portrait:
text="Portrait"
case .portraitUpsideDown:
text="PortraitUpsideDown"
case .landscapeLeft:
text="LandscapeLeft"
case .landscapeRight:
text="LandscapeRight"
default:
text="Another"
}
NSLog("You have moved: \(text)")
collectionView?.reloadData()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfCells
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if(indexPath.row==numberOfCells-1) {
if loadingStatus == .haveMore {
self.perform(#selector(ViewController.loadMore), with: nil, afterDelay: 0)
}
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: firstCellid, for: indexPath) as! VerticalCollectionViewCell
cell.menuHeaderLabel.text = "Labet text no \(indexPath.item)"
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.view.frame.width, height: 100)
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
var footerView:VerticalCollectionViewCell2!
if (kind == UICollectionElementKindSectionFooter) && (loadingStatus != .finished) {
footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: firstFooterCellid, for: indexPath) as! VerticalCollectionViewCell2
}
return footerView
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return (loadingStatus == .finished) ? CGSize.zero : CGSize(width: self.view.frame.width, height: 50)
}
}
class VerticalCollectionViewCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let menuHeaderLabel: UILabel = {
let label = UILabel()
label.text = "lable text"
label.textColor = .orange
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 15)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
func setupCell() {
addSubview(menuHeaderLabel)
// addTaskButton.addTarget(self, action: #selector(MenuHeader.addTask), for: .touchUpInside)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-8-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": menuHeaderLabel]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-5-[v0(30)]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": menuHeaderLabel]))
}
}

Infinite Scroll in collectionView swift programmatically

i want to infinite scrolling 10 images in collectionView programmatically of swift. the image came from web by json according to my choice. i have been unable to scrolling 20 image in a times.
here is my code
import Foundation
import UIKit
let categoryCellid = "categoryCellid"
class ProductByCategoryCollectionView: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var headercellId = "headercellId"
var callCategoryObject = [Product]()
func getPropductListByCategory(){
// has api code, that was well
}
override func viewDidLoad() {
super.viewDidLoad()
self.getPropductListByCategory()
collectionView?.backgroundColor = .white
navigationItem.title = "Product"
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil)
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Sort By", style: .plain, target: nil, action: nil)
self.setupHeaderView()
collectionView?.register(ProductByCategoryCollectionViewCell.self, forCellWithReuseIdentifier: categoryCellid)
}
func showCategoryDetailSegue() {
let detailcontroller = UIViewController()
navigationController?.pushViewController(detailcontroller, animated: true)
}
func sortBtnTarget() {
}
func filterBtnTarget() {
}
let dividedLine: UIView = {
let view = UIView()
view.backgroundColor = UIColor(white: 0.4, alpha: 0.4)
return view
}()
let totalItemLabel: UILabel = {
let label = UILabel()
label.text = ""
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 15)
label.backgroundColor = UIColor.white
return label
}()
let dividerLineView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.white
return view
}()
func setupHeaderView(){
view.backgroundColor = UIColor(white: 0.4, alpha: 0.4)
dividedLine.frame = CGRect(x: 0, y: 95, width: view.frame.width, height: 1)
totalItemLabel.frame = CGRect(x: 0, y: 55, width: view.frame.width, height: 40)
view.addSubview(totalItemLabel)
view.addSubview(dividedLine)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return callCategoryObject.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: categoryCellid, for: indexPath) as! ProductByCategoryCollectionViewCell
cell.callProductObject4Cell = callCategoryObject[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 172, height: 300)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(32, 10, 0, 10)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let controller1 = DetailsController(collectionViewLayout: layout)
navigationController?.pushViewController(controller1, animated: true)
}
}
class ProductByCategoryCollectionViewCell: UICollectionViewCell {
var callProductObject4Cell: Product? {
didSet {
productLabel.text = callProductObject4Cell?.name
// priceLabel.text = String(describing: callProductObject4Cell?.price)
if let price = callProductObject4Cell?.price {
priceLabel.text = "$\(price)"
} else {
priceLabel.text = ""
}
if let profileImageUrl = callProductObject4Cell?.image {
productImage.loadImageUsingUrlString(profileImageUrl)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupcategoryCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let productImage: UIImageView = {
let image = UIImageView()
image.image = UIImage(named: "default")
image.contentMode = .scaleAspectFit
image.layer.borderWidth = 1
image.layer.borderColor = UIColor.orange.cgColor
image.layer.masksToBounds = true
return image
}()
let productLabel: UILabel = {
let label = UILabel()
label.text = "productName"
label.textColor = .black
label.numberOfLines = 0
label.font = UIFont.boldSystemFont(ofSize: 10)
return label
}()
let priceLabel: UILabel = {
let label = UILabel()
// label.backgroundColor = .lightGray
label.text = ""
label.textColor = .orange
label.font = UIFont.systemFont(ofSize: 13)
return label
}()
func setupcategoryCell() {
addSubview(productImage)
addSubview(productLabel)
addSubview(priceLabel)
addConstraintsWithFormat("H:|[v0]|", views: productImage)
addConstraintsWithFormat("V:|[v0(230)]-2-[v1][v2(10)]-5-|", views: productImage,productLabel, priceLabel)
addConstraintsWithFormat("H:|[v0]|", views: productLabel)
addConstraintsWithFormat("H:|[v0]|", views: priceLabel)
}
}
Use this code for an infinite UIScrollView:
import Foundation
import UIKit
enum LoadMoreStatus {
case loading
case finished
case haveMore
}
class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var verticalDataSource = [String]()
var firstCellid = "firstcellid"
var firstFooterCellid = "firstfootercellid"
var numberOfCells = 5
var loadingStatus = LoadMoreStatus.haveMore
func reloadData() {
//numberOfCells = 10
collectionView?.reloadData()
if numberOfCells > 0 {
collectionView?.scrollToItem(at: IndexPath(row: 0, section: 0), at: .left, animated: true)
}
}
func loadMore() {
if numberOfCells >= 40 {
// here will show untill finished number
loadingStatus = .finished
collectionView?.reloadData()
return
}
// Replace code with web service and append to data source
Timer.schedule(delay: 2) { timer in
self.numberOfCells += 2
self.collectionView?.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
collectionView?.register(VerticalCollectionViewCell.self, forCellWithReuseIdentifier: firstCellid)
collectionView?.register(VerticalCollectionViewCell2.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: firstFooterCellid)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK - Rotation methods
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
var text=""
switch UIDevice.current.orientation {
case .portrait:
text="Portrait"
case .portraitUpsideDown:
text="PortraitUpsideDown"
case .landscapeLeft:
text="LandscapeLeft"
case .landscapeRight:
text="LandscapeRight"
default:
text="Another"
}
NSLog("You have moved: \(text)")
collectionView?.reloadData()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfCells
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if(indexPath.row==numberOfCells-1) {
if loadingStatus == .haveMore {
self.perform(#selector(ViewController.loadMore), with: nil, afterDelay: 0)
}
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: firstCellid, for: indexPath) as! VerticalCollectionViewCell
cell.menuHeaderLabel.text = "Labet text no \(indexPath.item)"
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.view.frame.width, height: 100)
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
var footerView:VerticalCollectionViewCell2!
if (kind == UICollectionElementKindSectionFooter) && (loadingStatus != .finished) {
footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: firstFooterCellid, for: indexPath) as! VerticalCollectionViewCell2
}
return footerView
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return (loadingStatus == .finished) ? CGSize.zero : CGSize(width: self.view.frame.width, height: 50)
}
}
class VerticalCollectionViewCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let menuHeaderLabel: UILabel = {
let label = UILabel()
label.text = "lable text"
label.textColor = .orange
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 15)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
func setupCell() {
addSubview(menuHeaderLabel)
// addTaskButton.addTarget(self, action: #selector(MenuHeader.addTask), for: .touchUpInside)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-8-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": menuHeaderLabel]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-5-[v0(30)]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": menuHeaderLabel]))
}
}
class VerticalCollectionViewCell2: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
setupCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let menuHeaderLabel: UILabel = {
let label = UILabel()
label.text = "loadin more waiting"
label.textColor = .green
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 15)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
func setupCell() {
addSubview(menuHeaderLabel)
// addTaskButton.addTarget(self, action: #selector(MenuHeader.addTask), for: .touchUpInside)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-8-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": menuHeaderLabel]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-5-[v0(30)]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": menuHeaderLabel]))
}
}
extension Timer {
class func schedule(delay: TimeInterval, handler: #escaping (Timer!) -> Void) -> Timer {
let fireDate = delay + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
return timer!
}
class func schedule(repeatInterval interval: TimeInterval, handler: #escaping (Timer!) -> Void) -> Timer {
let fireDate = interval + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
return timer!
}
}

ImageView of a custom CollectionViewCell is nil when it should be configured

I have a tableViewCell with a collectionView, collectionView's cells are custom ones, they contains just a imageView.
Here is my test project
Here are DataSource required methods from my CollectionView class:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
let image = UIImage(named: listItems[indexPath.row])
cell.testImageView.image = image
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return listItems.count
}
When I try to set image for cell's imageView I get this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
I have checked image, it isn't nil, but testImageView is, I get this error when I try to set image to collectionViewCell's testImageView.
How can I fix it?
EDIT1
Here is method called from tableViewController to fill collectionView's listItem
func load(listItem: [String]) {
self.listItems = listItem
reloadData()
}
Also if I remove code from collectionView cellForItemAt indexPath with this one all is working fine
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath)
let imageView = UIImageView(image:UIImage(named: listItems[indexPath.row]))
cell.backgroundView = imageView
You have mistaken your two view controllers. Your IB outlet is connected to a cell in a different view controller. I mean you can have multiple views in different controllers connected to a same IBOutlet, but in your case the one that loads first is not connected, so that is why it crashes.
This is the cell your outlet was connected to.
This is that you are trying to load (but did not connect IBOutlet to image view):
Just in case you want to use code instead..
import UIKit
class ImageCell : UICollectionViewCell {
private var imageView: UIImageView!
private var descLabel: UILabel!
public var image: UIImage? {
get {
return self.imageView.image
}
set {
self.imageView.image = newValue
}
}
public var imageDesc: String? {
get {
return self.descLabel.text
}
set {
self.descLabel.text = newValue
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initControls()
self.setTheme()
self.doLayout()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initControls()
self.setTheme()
self.doLayout()
}
override func awakeFromNib() {
super.awakeFromNib()
}
func initControls() {
self.imageView = UIImageView()
self.descLabel = UILabel()
}
func setTheme() {
self.imageView.contentMode = .scaleAspectFit
self.descLabel.numberOfLines = 1
self.descLabel.lineBreakMode = .byWordWrapping
self.descLabel.textAlignment = .center
self.descLabel.textColor = UIColor.black
self.contentView.backgroundColor = UIColor.white
}
func doLayout() {
self.contentView.addSubview(self.imageView)
self.contentView.addSubview(self.descLabel)
self.imageView.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 5).isActive = true
self.imageView.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: -5).isActive = true
self.imageView.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 0).isActive = true
self.descLabel.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 5).isActive = true
self.descLabel.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: -5).isActive = true
self.descLabel.topAnchor.constraint(equalTo: self.imageView.bottomAnchor, constant: 5).isActive = true
self.descLabel.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -5).isActive = true
for view in self.contentView.subviews {
view.translatesAutoresizingMaskIntoConstraints = false
}
}
}
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
private var collectionView: UICollectionView!
private var dataSource: Array<String>!
override func viewDidLoad() {
super.viewDidLoad()
self.initDataSource()
self.initControls()
self.setTheme()
self.registerClasses()
self.doLayout()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func initDataSource() {
self.dataSource = ["Image1", "Image2", "Image3", "Image4", "Image5", "Image6"]
}
func initControls() {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 117, height: 125)
layout.invalidateLayout()
self.collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
self.collectionView.delegate = self
self.collectionView.dataSource = self
}
func setTheme() {
self.collectionView.backgroundColor = UIColor.clear
self.edgesForExtendedLayout = UIRectEdge(rawValue: 0)
self.view.backgroundColor = UIColor.blue
}
func registerClasses() {
self.collectionView.register(ImageCell.self, forCellWithReuseIdentifier: "ImageCellIdentifier")
}
func doLayout() {
self.view.addSubview(self.collectionView)
self.collectionView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.collectionView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
for view in self.view.subviews {
view.translatesAutoresizingMaskIntoConstraints = false
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
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: "ImageCellIdentifier", for: indexPath) as! ImageCell
let imageName = self.dataSource[indexPath.row]
cell.image = UIImage(named: imageName)
cell.imageDesc = imageName
return cell
}
}
http://imgur.com/o7O7Plw
maybe the "testImageView" outlet variable is not connected from the interface builder or there is no CollectionViewCell with reuseIdentifier "ImageCell". Check whether cell is nil or not using LLDB po command.

Resources