UIImageView passing (segue) nil to another ViewController - ios

after a day of researching and trying stuff, I come to your aid.
I have a collectionView passing an image to an imageView, just like instagram (for you to imagine the interface), I THINK I'm performing the segue right, but on the other viewController it ends up NIL.
My code is as follows:
First View Controller >
// TakePhotoViewController.swift
import UIKit
import Photos
class TakePhotoViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
#IBOutlet weak var photoImageView: UIImageView!
var imageArray = [UIImage]()
override func viewDidLoad(){
super.viewDidLoad()
grabPhotos()
}
#IBAction func postPhotoTaken(_ sender: Any) {
self.performSegue(withIdentifier: "photoPost", sender: self)
}
func grabPhotos(){
let imgManager = PHImageManager.default()
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true
requestOptions.deliveryMode = .highQualityFormat
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
if let fetchResult: PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions){
if fetchResult.count > 0 {
for i in 0..<fetchResult.count{
imgManager.requestImage(for: fetchResult.object(at: i), targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: requestOptions, resultHandler: {image, error in
self.imageArray.append(image!)
})
}
}
else {
print("You Don't Have Any Photos!")
}
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = imageArray[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
photoImageView.image = imageArray[indexPath.row]
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.frame.width / 3 - 1
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "photoPost" {
let photoPost = segue.destination as! PhotoPostTableViewController
let imagePhoto = self.photoImageView.image
photoPost.photo = imagePhoto!
}
}
}
Second View Controller >
// photoPostViewController.swift
import UIKit
class PhotoPostTableViewController: UITableViewController {
var photo: UIImage!
#IBOutlet weak var newPhoto: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
newPhoto.image = photo
print(photo)
}
override func viewDidAppear(_ animated: Bool) {
newPhoto.image = photo
print(photo)
}
}
Can you guys help me?

Based on the fact that the segue.identifier in your prepare(for:) returns nil, that means the segue performed is triggered by the storyboards, not by the postPhotoTaken(_ sender: Any).
Check the storyboard, and find the segue that goes from first VC to second VC and is triggered by the button, and change it's identifier to "photoPost".
I believe after that you can delete postPhotoTaken(_ sender: Any).

Related

SWIF Error Message: Instantiated view controller ... but didn't get a UICollectionView.'

I am getting an error message that is typically associated with a missing IBOutlet but when I add one I get even more errors. I have found a few answers on SO but none of them have worked. What am I doing wrong?
Error Message:
Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason:
'-[UICollectionViewController loadView] instantiated view controller
with identifier "UIViewController-BYZ-38-t0r" from storyboard "Main",
but didn't get a UICollectionView.'
import UIKit
import Photos
private let reuseIdentifier = "Cell"
class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var imageArray = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
grabPhotos()
}
func grabPhotos(){
let imgManager = PHImageManager.default()
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true
requestOptions.deliveryMode = .highQualityFormat
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions){
if fetchResult.count > 0 {
for i in 0..<fetchResult.count{
imgManager.requestImage(for: fetchResult.object(at: i), targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: requestOptions, resultHandler: {
image, error in
self.imageArray.append(image!)
})
}
} else {
print("you do not have any photos")
self.collectionView?.reloadData()
}
}
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return imageArray.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 0
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = imageArray[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.frame.width / 3 - 1
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
}
When you start a new project, Xcode gives you a default UIViewController with custom class ViewController:
You cannot simply change the class to:
class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
Instead, delete the default controller from your Storyboard and add a new UICollectionViewController:
Note that the Custom Class shows as UICollectionViewController (in gray, because it is the default class). You can now change that to ViewController (and on the Attributes Inspector pane set it as Is Initial View Controller).

Collection view auto resizing and setup repeating background

I am using collection view to load data from API. Here i want to extend size of collection view height instead of scrolling inside collection view. And also need to repeat the background image according to collection view height.
Here is the android layout and i want to develop similar to this.Tap here
import UIKit
import Nuke
import SVProgressHUD
import JSONJoy
class HomeViewController: UIViewController {
#IBOutlet weak var categoryCollection: UICollectionView!
#IBOutlet weak var tabbar: UITabBar!
var sectors:[Sector] = []
var timer = Timer()
var counter = 0
var selectedSector = ""
var selectedSectorName = ""
var webService = ApiService()
let plist = PlistHelper()
override func viewDidLoad() {
super.viewDidLoad()
self.categoryCollection.dataSource = self
self.categoryCollection.delegate = self
for item in tabbar.items ?? []{
item.image = item.image?.withRenderingMode(.alwaysOriginal)
}
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: .selected)
listSectors()
self.categoryCollection.backgroundColor = UIColor(patternImage: UIImage(named: "bg")!)
}
override func viewWillAppear(_ animated: Bool) {
listbanners()
}
override func viewWillDisappear(_ animated: Bool) {
self.timer.invalidate()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "sectors"){
let vc = segue.destination as! SectorsViewController
vc.sectorCode = selectedSector
vc.sectorName = selectedSectorName
}
}
func listSectors(){
webService.listSectors({ (sectors, message, status) in
if(status){
if let resData = sectors.arrayObject {
do{
for data in resData{
self.sectors.append(try Sector(JSONLoader(data)))
}
DispatchQueue.main.async {
self.categoryCollection.reloadData()
}
}
catch let error {
print("JSonJoyError:\(error)")
}
}
}
})
}
}
extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if(collectionView == bannerCollection){
return banners.count
}
else {
return sectors.count
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let options = ImageLoadingOptions(placeholder: UIImage(named: "bannerPlaceholder"),transition: .fadeIn(duration: 0.33))
if(collectionView == bannerCollection){
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! DataCollectionViewCell
Nuke.loadImage(with: URL(string: banners[indexPath.row].ImageUrl ?? "")!, options: options, into:cell.img)
return cell
}
else{
let cell = categoryCollection.dequeueReusableCell(withReuseIdentifier: "catCell", for: indexPath) as! catogeryCollectionViewCell
Nuke.loadImage(with: URL(string: sectors[indexPath.row].ImageUrl ?? "")!, options: options, into:cell.photoImageView)
return cell
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if(collectionView == categoryCollection){
selectedSector = sectors[indexPath.row].Code ?? "FOOD"
selectedSectorName = sectors[indexPath.row].Name ?? "FOOD"
self.performSegue(withIdentifier: "sectors", sender: self)
}
}
}
extension HomeViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if(collectionView == bannerCollection){
let size = bannerCollection.frame.size
return CGSize(width: size.width, height: size.height - 10)
}
else{
let size = categoryCollection.frame.size
print("size\(size)")
return CGSize(width: (size.width / 2) - 8, height:120)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 30
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
}
Following steps can help you to increase your collection View height according to data.
Create Heightconstraint outlet.
After loading data in collection view with delay of 0.2 sec in main thread,
Set Height Constraint constant = collection view content size height.

I want create this Sliding UIVies in xcode using swift, what sholud i used ? an collecntionView or TableView?

i want to create an exact screen in my ios application with xcode & swift im not able to create it, what shall i used? an collectionView or ScroolView?
import UIKit
class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
#IBOutlet weak var newCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
newCollectionView.delegate = self
newCollectionView.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: view.frame.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
It is my class. It works completely. Also i added an image of storyboard. Link to my github project : https://github.com/Agisight/scroller.git
class ViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet weak var scroll: UIScrollView!
#IBOutlet var btns: [UIView]!
override func viewDidLoad() {
super.viewDidLoad()
scroll.delegate = self
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
methodAnimation()
}
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
methodAnimation()
}
func methodAnimation() {
if btns.count == 0 {return}
var i = 0
// i – calculate it, it is your visible/desirable view.
// here is variant of code
let dragOffset = view.frame.width * 0.5 // callibrate it for you
let offX = scroll.contentOffset.x
i = Int(offX + dragOffset) / Int(view.frame.width)
i = max(0, min(i, btns.count - 1))
let yourX = btns[i].frame.width * CGFloat(i) // ()
let p = CGPoint(x: yourX, y: 0);
scroll.setContentOffset(p, animated: true)
}
}

How can I check if the core data is empty?

I am using core data to populate a collection view. Now i want to check if it is empty or not. I want to do additional stuff if it is empty. How can I achieve that?
if myJokes.isEmpty == true {
noFavorites.isHidden = false
}
I have tried to check it likes this but it did not work:
class ViewController2: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {
var myJokes : [MyJokes] = []
override func viewDidLoad() {
super.viewDidLoad()
getData()
myCollectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return myJokes.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell2
if myJokes.isEmpty == true {
noFavorites.isHidden = false
}
cell.backView.layer.cornerRadius = 10
let task = myJokes[indexPath.row]
cell.textLabel.text = task.favoriteJokes!
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: myCollectionView.frame.width, height: 58)
}
func getData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
myJokes = try context.fetch(MyJokes.fetchRequest())
} catch {}
}
#IBAction func menuBtnPressed(_ sender: Any) {
if menuShowing {
menuConstraint.constant = -171
UIView.animate(withDuration: 0.4, animations: {
self.view.layoutIfNeeded()
})
}

View is calling viewDidLoad() when navigating back

When the user selects a cell in the collection view, it pushes to a new view controller for that cell.
The problem is that when the user swipes back, the collection view controller runs viewDidLoad() instead of viewDidAppear(). This causes the whole collection view to reload and go back up to the top (first cell) and the user has to scroll all the way back down to get to where they were before.
Does anyone know why this is happening??
import UIKit
import FirebaseStorage
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let reuseIdentifier = "PostCell"
var post: [Post] = [Post]()
var imageURLs: [URL] = [URL]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.hidesBarsOnSwipe = true
collectionView?.backgroundColor = UIColor(red: 0.91, green: 0.91, blue: 0.91, alpha: 1.00)
// Uncomment the following line to preserve selection between presentations
self.clearsSelectionOnViewWillAppear = false
// Register cell classes
collectionView?.register(PostCell.self, forCellWithReuseIdentifier: reuseIdentifier)
//setupHorizontalBar()
setupCollectionView()
// Get all of the posts
loadPosts()
print("loaded")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
print("appeared")
collectionView.index
}
func setupCollectionView() {
if let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
layout.scrollDirection = .vertical
layout.minimumLineSpacing = 0
}
}
func loadPosts() {
postRef.observe(.value, with: { (snapshot) in
for eachPost in snapshot.value as! [String: Any] {
let dict: Dictionary<String, Any> = [eachPost.key: eachPost.value]
let post = Post(postDictionary: dict)
print(post)
self.posts.append(post)
self.collectionView?.reloadData()
}
})
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return posts.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PostCell
//cell.backgroundColor = .brown
let post = posts[indexPath.row]
cell.nameLabel.text = post.name
let details = "\n\(post.address!)\n\n\(post.time!) \(post.date!)"
cell.postDetailTextView.text = details
if let imageURL = post.image {
print(imageURL)
cell.postImageView.sd_setImage(with: URL(string: imageURL))
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height = (self.view.frame.width - 20) * 9 / 16
return CGSize(width: self.view.frame.width, height: height + 5 + 140)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
When didSelectItemAt is called, I want the navigation controller to push to another view controller for the cell selected.
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(indexPath)
let detailVC = DetailViewController()
self.navigationController?.pushViewController(detailVC, animated: true)
}
}

Resources