How to pass array of data between UIViewControllers from #objc function - ios

I have a Child UICollectionViewController where I have an array of images.
When I delete any photo I want to send back that array of updated images to Parent UIViewController.
Also in Child controller I have a programatically view which is called when I click on any image to expand it. When the image is expanded the user can click on a Delete button to delete photos from that array.
My array is updated correctly after delete but I can't manage to send it back to parent for some reasons.
I tried to send it back using Delegates and Protocols.
Here is my code for child controller:
protocol ListImagesDelegate {
func receiveImagesUpdated(data: [String]?)
}
class ListImagesVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
// Properties
var receivedImagesPath: [String]? = []
var fullscreenImageView = UIImageView()
var indexOfSelectedImage = 0
var imagesAfterDelete: [String]? = []
var delegate: ListImagesDefectDelegate?
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("imagesAfterDelete: \(imagesAfterDelete ?? [])") // I'm getting the right number of images in this array.
delegate?.receiveImagesUpdated(data: imagesAfterDelete)
}
...
...
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Click on photo: \(indexPath.item + 1)")
if let imagePath = receivedImagesPath?[indexPath.item] {
guard let selectedImage = loadImageFromDiskWith(fileName: imagePath) else {return}
setupFullscreenImageView(image: selectedImage)
indexOfSelectedImage = indexPath.item
}
}
private func setupFullscreenImageView(image: UIImage){
fullscreenImageView = UIImageView(image: image)
fullscreenImageView.frame = UIScreen.main.bounds
fullscreenImageView.backgroundColor = .black
fullscreenImageView.contentMode = .scaleAspectFit
fullscreenImageView.isUserInteractionEnabled = true
self.view.addSubview(fullscreenImageView)
self.navigationController?.isNavigationBarHidden = true
self.tabBarController?.tabBar.isHidden = true
let deleteButton = UIButton(frame: CGRect(x: fullscreenImageView.bounds.maxX - 50, y: fullscreenImageView.bounds.maxY - 75, width: 30, height: 40))
deleteButton.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]
deleteButton.backgroundColor = .black
deleteButton.setImage(UIImage(named: "trashIcon"), for: .normal)
deleteButton.addTarget(self, action: #selector(deleteButtonTapped), for: .touchUpInside)
fullscreenImageView.addSubview(deleteButton)
}
#objc func deleteButtonTapped(button: UIButton!) {
print("Delete button tapped")
receivedImagesPath?.remove(at: indexOfSelectedImage)
imagesAfterDelete = receivedImagesPath
collectionView.reloadData()
self.navigationController?.isNavigationBarHidden = false
self.tabBarController?.tabBar.isHidden = false
fullscreenImageView.removeFromSuperview()
}
Here is the Parent controller:
var updatedImages: [String]? = []
...
...
extension NewAlbumVC: ListImagesDelegate {
func receiveImagesUpdated(data: [String]?) {
print("New array: \(data ?? [])") // This print is never called.
updatedImages = data
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToImages" {
let listImagesVC = segue.destination as! ListImagesVC
listImagesVC.delegate = self
}
}
}
I want to specify that my child controller have set a Storyboard ID ("ListImagesID") and also a segue identifier from parent to child ("goToImages"). Can cause this any conflict ?
Thanks if you read this.

It appears that the delegate is nil here
delegate?.receiveImagesUpdated(data: imagesAfterDelete)
For this
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
to trigger you must have
self.performSegue(withIdentifier:"goToImages",sender:nil)
Edit: This
let listImagesDefectVC = storyboard?.instantiateViewController(withIdentifier: "ListImagesDefectID") as! ListImagesDefectVC
listImagesDefectVC.receivedImagesPath = imagesPath
navigationController?.pushViewController(listImagesDefectVC, animated: true)
doesn't trigger prepareForSegue , so add
listImagesDefectV.delegate = self
So finally
Solution 1 :
#objc func tapOnImageView() {
let listImagesDefectVC = storyboard?.instantiateViewController(withIdentifier: "ListImagesDefectID") as! ListImagesDefectVC
listImagesDefectVC.receivedImagesPath = imagesPath
listImagesDefectVC.delegate = self
navigationController?.pushViewController(listImagesDefectVC, animated: true)
}
Solution 2 :
#objc func tapOnImageView() {
self.performSegue(withIdentifier:"goToImages",sender:nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToImages" {
let listImagesVC = segue.destination as! ListImagesVC
listImagesVC.receivedImagesPath = imagesPath
listImagesVC.delegate = self
}
}

Related

Swift: Update Button.setTitle and current UIPageView with NSNotification

Swift 4: I'm using NSNotification post and observe an object between two view controller. My issue is updating the viewController that observes given the received object.
There are two things that needs updating 1. setTitle of a button, 2. the current page on UIPageViewController. How do i update these two things?
I've worked on this the whole day today and yesterday, with no results.
I've tried using struct to do the updating and normal variables.
**YellowViewController - Observes -> Issue here**
let searchedReturnedKey = "Searched"
class YellowViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
let pageView = PageView()
let searched = Notification.Name(rawValue: searchedReturnedKey)
private var isAnimating = false
struct structure {
static var SearchedIndex = Int()
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
setupUIPageView()
setupNavigationBarItem()
createObserver()
}
func createObserver(){
NotificationCenter.default.addObserver(self, selector: #selector(YellowViewController.updateVerseView(notification:)), name: searched, object: nil)
}
#objc func updateVerseView(notification: NSNotification) {
print("Observed")
structure.SearchedIndex = notification.object as! Int
let chapterIndexLabel = doneModel.ChapterIndex
let verseList = doneModel.chapterVerses
let pageView = PageView()
// HERE IS MY ISSUE - booklabel.text and pageview.verses
bookLabel.text = chapterIndexLabel[structure.SearchedIndex]
pageView.verses = verseList[structure.SearchedIndex]
print(structure.SearchedIndex, "Index")
}
func setupUIPageView() {
let verseList = bibleModel.chapterVerses
let chapterIndexLabel = bibleModel.ChapterIndex
let pageViewControllers = [pageView] // Important! UIPageViewController sets ViewController in a list to enable swiping. - Understand this.
pageView.verses = verseList.first! // Important! Setups verses for first view.
bookLabel.text = chapterIndexLabel.first!
setViewControllers(pageViewControllers, direction: .forward, animated: true, completion: nil)
}
var bookLabel = UILabel()
func setupLeftNavItems() {
let bookButton = UIButton(type: .system)
bookButton.setTitle(bookLabel.text! + " 1", for: .normal)
bookButton.setTitleColor(goldColor, for: .normal)
bookButton.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 18)
bookButton.addTarget(self, action: #selector(handleSearch), for: .touchUpInside)
// bookButton.frame = CGRect(x: 30, y: 0, width: 54, height: 34)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: bookButton)
}
#objc func handleSearch() { // Handles openeing SearchViewController
let searchViewController = SearchViewController()
let navController = UINavigationController(rootViewController: searchViewController)
present(navController, animated: true, completion: nil)
}
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
isAnimating = true
}
// Handles swiping right - To next chapter.
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if isAnimating {
return nil
}
let verseList = bibleModel.chapterVerses
let currentVerseView = (viewController as! PageView).verses
let currentIndex = verseList.index(of: currentVerseView)
let chapterIndexLabel = doneModel.ChapterIndex
if currentIndex! < verseList.count - 1 {
let pageView = PageView()
pageView.verses = verseList[currentIndex! + 1 ]
bookLabel.text = chapterIndexLabel[currentIndex! + 1]
print("Swiped right")
setupLeftNavItems()
createObserver()
return pageView
}
return nil
}
// Handles swiping left - To previous chapter
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if isAnimating {
return nil
}
let verseList = bibleModel.chapterVerses
let currentVerseView = (viewController as! PageView).verses
let currentIndex = verseList.index(of: currentVerseView)
let chapterIndexLabel = doneModel.ChapterIndex
if currentIndex! > 0 {
let pageView = PageView()
pageView.verses = verseList[currentIndex! - 1]
bookLabel.text = chapterIndexLabel[currentIndex! - 1]
setupLeftNavItems()
print("Swiped left")
createObserver()
return pageView
}
return nil
}
}
SearchViewController - Post
class SearchViewController: UITableViewController, UISearchBarDelegate {
let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.titleView = navSearchBar
setupView()
}
func setupView() {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
tableView.delegate = self
tableView.dataSource = self
navSearchBar.delegate = self
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Books.count
}
**I post the data from this function**
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
let cellLabelContent = cell!.textLabel!.text
let cellLabelIndex = Books.firstIndex(of: cellLabelContent!)
print("Book name:", cellLabelContent!, "index:", cellLabelIndex!)
let notificationName = Notification.Name(rawValue: searchedReturnedKey)
NotificationCenter.default.post(name: notificationName, object: cellLabelIndex)
dismiss(animated: true, completion: nil)
}
}
Actual result -> No update
Expected result -> Update given object
To be able to update the current view of your UIPageViewController, you would need to do this inside your updateVerseView. The setViewControllers method is correct and efficient method to update a view inside a UIPageViewController.
let pageViewControllers = [pageView]
pageView.verses = verseList[structure.searchedIndex]
setViewControllers(pageViewControllers, direction: .forward, animated: true, completion: nil)
To update your bookLabel.txt you would just need to call your setupLeftNavItems() function.
Here you need toaddObserver with your selector #selector(YellowViewController.updateVerseView(notification:)
I think you set wrong ViewController name

Swift 4 start with custom ViewController

I have chatting app. I decide to create SlideShow tutorial for it. Now I have problem. How can I run TutorialVC just once when user install the app?
Usually app starts with AuthVC. Now I want to run tutorialVC just once, and then when user close app and run it again, from auth like usually.
My tutorial VC:
class TutorialViewController: UIViewController, UIScrollViewDelegate {
#IBAction func understandButtonAction(_ sender: Any) {
}
#IBOutlet weak var understandButton: UIButton!
#IBOutlet weak var tutorialPageControl: UIPageControl!
#IBOutlet weak var tutorialScrollView: UIScrollView!
var images: [String] = ["1","2","3","4"]
var frame = CGRect(x: 0, y: 0, width: 0, height: 0)
override func viewDidLoad() {
super.viewDidLoad()
setup()
addSlider()
setupButton()
}
//===============================
//EVTAuthorizationViewController
//===============================
override func viewWillAppear(_ animated: Bool) {
UIApplication.shared.keyWindow?.windowLevel = UIWindowLevelStatusBar
}
override func viewWillDisappear(_ animated: Bool) {
UIApplication.shared.keyWindow?.windowLevel = UIWindowLevelNormal
}
//AddButton
func setupButton(){
understandButton.layer.cornerRadius = 20
}
#IBAction func buttonAction(_ sender: Any?) {
print("Successful")
}
//ScrollBars
func setup(){
self.understandButton.isHidden = true
tutorialScrollView.showsHorizontalScrollIndicator = false
tutorialScrollView.showsVerticalScrollIndicator = false
}
//ScrollView method
//=============================
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
var pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width
tutorialPageControl.currentPage = Int(pageNumber)
if tutorialPageControl.currentPage == 3{
self.understandButton.isHidden = false
}else{
self.understandButton.isHidden = true
}
}
//Addslider with photo
func addSlider(){
tutorialPageControl.numberOfPages = images.count
for index in 0..<images.count{
let xPos = self.view.frame.size.width * CGFloat(index)
frame.origin.x = tutorialScrollView.frame.size.width * CGFloat(index)
//frame.size = view.frame.size
let imageView = UIImageView(frame: CGRect(x: xPos, y: 0, width: self.view.frame.width, height: self.view.frame.size.height))
imageView.image = UIImage(named: images[index])
imageView.contentMode = .scaleAspectFill
self.tutorialScrollView.addSubview(imageView)
}
tutorialScrollView.contentSize = CGSize(width: (view.frame.size.width * CGFloat(images.count)), height: view.frame.size.height)
tutorialScrollView.delegate = self
}
}
Use userDefaults. I suppose the understandButton is the button the user hits to skip the tutorial, so when when it's tapped set a true bool value for a key that you are going to use, here I've chosen "tutorial presented":
#IBAction func understandButtonAction(_ sender: Any) {
UserDefaults.standard.set(true, forKey: "tutorial presented")
}
and when the app launches, in the AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
let window = (UIApplication.shared.delegate as! AppDelegate).window
let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
if UserDefaults.standard.bool(forKey: "tutorial presented") == true {
let controller = storyboard.instantiateViewController(withIdentifier: "Your Navigation controller name")
window?.rootViewController = tutorialViewController()
} else {
let tutorial = storyboard.instantiateViewController(withIdentifier: "Your tutorial controller name")
window?.rootViewController = tutorial
}
window?.makeKeyAndVisible()
return true
}
You can use a flag and store it via NSUserDefaults.
extension UserDefaults {
private static let didLaunchAppOnceKey = "didLaunchAppOnce"
var didLaunchAppOnce: Bool {
get { return bool(forKey: UserDefaults.didLaunchAppOnceKey) }
set { set(newValue, forKey: UserDefaults.didLaunchAppOnceKey) }
}
}
Then before presenting your view controller, check if the flag is set:
if !UserDefaults.standard.didLaunchAppOnce {
// Set the flag to true, so on next launch, we won't enter in the if again
UserDefaults.standard.didLaunchAppOnce = true
// Present your VC
…
}

UITextField doesn't end editing in a UITableViewCell in Swift 4

I am still new to swift and I would ask you for advice. Thank you in advance and sorry for my bad English.
My goal is:
User tap edit button in the table's row. UITextField appears instead cell. After entering value and pressing Return key UITextField disappears again and cell is recalculated.
editButton pressed -> hide priceCell & show UITextField & show keyboard & start editing/entering value (blinking cursor) -> stop editing/entering value execute by pressing Return key -> hide UITextField & shows priceCell & save entered value into array & reload edited row
I use this answer as starting blueprint.
I would like to also use .decimalPad keyboard to easier entering numeric value and limit user to use only numbers (and decimal point), but this exclude use Return key as stop editing, am I right?
I found this possible solution, but it seems to me complex for my problem...
my ViewController:
import UIKit
class PortfolioViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, PortfolioCellDelegate {
let getData = GetData()
...
override func viewDidLoad() {
super.viewDidLoad()
cellTableView.delegate = self
cellTableView.dataSource = self
cellTableView.register(UINib(nibName: "PortfolioCell", bundle: nil), forCellReuseIdentifier: "portfolioCell")
self.currencyControl.selectedSegmentIndex = MyVariables.currencyControlSelected
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let coinCell = tableView.dequeueReusableCell(withIdentifier: "portfolioCell", for: indexPath) as! PortfolioCell
...
coinCell.delegate = self
return coinCell
}
...
func portfolioButtonPressed(coinCell: PortfolioCell) {
let indexPath = self.cellTableView.indexPathForRow(at: coinCell.center)!
let selectedCell = cellTableView.cellForRow(at: indexPath) as! PortfolioCell
selectedCell.priceCell.isHidden = true
selectedCell.textCell.isHidden = false
selectedCell.textCell.delegate = self
func textFieldDidEndEditing(textField: UITextField) {
let owned: Double = Double(textField.text!)!
if owned >= 0 {
MyVariables.dataArray[indexPath.row].ownedCell = owned
} else {
MyVariables.dataArray[indexPath.row].ownedCell = 0.00
}
selectedCell.priceCell.isHidden = false
selectedCell.textCell.isHidden = true
self.cellTableView.reloadData()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
selectedCell.textCell.resignFirstResponder()
return true
}
}
...
}
my custom cell:
import UIKit
protocol PortfolioCellDelegate {
func portfolioButtonPressed(coinCell: PortfolioCell)
}
class PortfolioCell: UITableViewCell {
var delegate: PortfolioCellDelegate?
...
#IBAction func editCellPressed(_ sender: UIButton) {
delegate?.portfolioButtonPressed(coinCell: self)
}
...
}
For now when button is pressed proper UITextField shows, but don't dismiss after Return key is pressed.
Or should I change it completely and use tap gestures?
To end editing in any kind of scrollView, simply use this
cellTableView.keyboardDismissMode = .onDrag
or
cellTableView.keyboardDismissMode = .interactive
It will hide keyboard when you interact with the tableView
For number keypad you can add toolbar as a textField's inputAccessoryView. On toolbar add cancel button to dismiss keyboard.
There is two way to go:
1.) Delegate
2.) IQKeyboardManager
1.)
Use UITextFieldDelegate
There is one particular callback named "textFieldShouldEndEditing"
In this method, return true.
2.)
User the IQKeyboardManager one liner library. This library manages all the TextFields and scrollviews automatically. You activate it with one line in AppDelegate so it's easy to use.
https://github.com/hackiftekhar/IQKeyboardManager
Working but not as sleek as want it to be and also I was not capable to make IQKeyboardManager works so I did use inputAccessoryView.
custom cell:
import UIKit
protocol PortfolioCellDelegate {
func portfolioButtonPressed(didSelect coinCell: PortfolioCell)
func portfolioButtonPressed(coinCell:PortfolioCell, editingChangedInTextCell newValue:String)
}
class PortfolioCell: UITableViewCell, UITextFieldDelegate {
var delegate: PortfolioCellDelegate?
...
#IBAction func editCellPressed(_ sender: UIButton) {
textCell.becomeFirstResponder()
delegate?.portfolioButtonPressed(didSelect: self)
}
#IBAction func textCellValueChanged(_ sender: UITextField) {
if (sender.text?.isEmpty)! {
delegate?.portfolioButtonPressed(coinCell: self, editingChangedInTextCell: "XXX")
} else {
let text = sender.text
delegate?.portfolioButtonPressed(coinCell: self, editingChangedInTextCell: text!)
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.textCell.delegate = self
let flexiableSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.doneButtonAction))
let toolBar:UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: 35))
toolBar.barTintColor = UIColor(red:0.15, green:0.69, blue:0.75, alpha:1.0)
toolBar.tintColor = UIColor(red:0.93, green:0.93, blue:0.93, alpha:1.0)
toolBar.setItems([flexiableSpace, doneButton], animated: false)
textCell.inputAccessoryView = toolBar
textCell.keyboardType = UIKeyboardType.decimalPad
}
#objc func doneButtonAction() {
textCell.endEditing(true)
}
...
}
ViewController:
import UIKit
class PortfolioViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, PortfolioCellDelegate {
let getData = GetData()
...
override func viewDidLoad() {
super.viewDidLoad()
cellTableView.delegate = self
cellTableView.dataSource = self
cellTableView.register(UINib(nibName: "PortfolioCell", bundle: nil), forCellReuseIdentifier: "portfolioCell")
self.currencyControl.selectedSegmentIndex = MyVariables.currencyControlSelected
getData.delegate = self
timeStampLabel.text = MyVariables.timeStamp
}
override func viewDidAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.cellTableView.reloadData()
self.currencyControl.selectedSegmentIndex = MyVariables.currencyControlSelected
self.timeStampLabel.text = MyVariables.timeStamp
}
//MARK: - tableView
/***************************************************************/
...
func portfolioButtonPressed(coinCell: PortfolioCell, editingChangedInTextCell newValue: String) {
let indexPath = self.cellTableView.indexPathForRow(at: coinCell.center)!
let selectedCell = cellTableView.cellForRow(at: indexPath) as! PortfolioCell
selectedCell.priceCell.isHidden = false
selectedCell.textCell.isHidden = true
if newValue != "XXX" {
let owned: Double = Double(newValue)!
MyVariables.dataArray[indexPath.row].ownedCell = owned
}
selectedCell.priceCell.isHidden = false
selectedCell.textCell.isHidden = true
self.cellTableView.reloadRows(at: [indexPath], with: .automatic)
}
func portfolioButtonPressed(didSelect coinCell: PortfolioCell) {
let indexPath = self.cellTableView.indexPathForRow(at: coinCell.center)!
let selectedCell = cellTableView.cellForRow(at: indexPath) as! PortfolioCell
selectedCell.priceCell.isHidden = true
selectedCell.textCell.isHidden = false
}
...
}
It's easy: You should select that table view cell, then enable User Interaction Enabled in the attribute inspector.

Delete/remove displayed controller inside Page View Controller on clicking delete button, Swift

I am displaying images in a collection view controller. When the cell is tapped, I am passing those images to page view controller, where the user is given an option to delete or add image description as you can see in the below images.
When the user clicks delete button, I would the page (or view controller) to be deleted (just like the behaviour seen, when delete button is clicked in in Apple iOS photos app).
I tried to achieve it, by passing an array of empty view controller to pageViewController (See Code A), which resulted in a error
The number of view controllers provided (0) doesn't match the number required (1) for the requested transition which makes sense.
Am I on the right track, if yes, how can I fix the issue ?
If not, Is there a better approach to achieve the same ?
Code A: Taken from Code B
pageVC.setViewControllers([], direction: .forward, animated: true, completion: nil)
Code B: Taken from UserPickedImageVC
func deleteCurrentImageObject(){
guard let controllers = self.navigationController?.viewControllers else{
return
}
for viewController in controllers {
if viewController.className == "UserPickedImagesVC"{
let vc = viewController as! UserPickedImagesVC
let objectCount = vc.imageObjectsArray.count
guard objectCount > 0 && objectCount >= itemIndex else {
return
}
vc.imageObjectsArray.remove(at: itemIndex) // Removing imageObject from the array
if let pageVC = vc.childViewControllers[0] as? UIPageViewController {
pageVC.setViewControllers([], direction: .forward, animated: true, completion: nil)
}
}
}
}
Storyboard
Here is the complete code (except some custom UICollectionViewCell):
UserPickedImagesCVC.swift
import UIKit
import ImagePicker
import Lightbox
private let imageCellId = "imageCell"
private let addCellId = "addImagesCell"
class UserPickedImagesCVC: UICollectionViewController, ImagePickerDelegate, UserPickedImagesVCProtocol {
let imagePickerController = ImagePickerController()
//var userPickedImages = [UIImage]()
var userPickedImages = [ImageObject]()
override func viewDidLoad() {
super.viewDidLoad()
imagePickerController.delegate = self as ImagePickerDelegate
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
self.collectionView!.register(ImageCVCell .self, forCellWithReuseIdentifier: imageCellId)
self.collectionView!.register(ImagePickerButtonCVCell.self, forCellWithReuseIdentifier: addCellId)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return userPickedImages.count + 1
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let item = indexPath.item
print("item: \(item)")
if item < userPickedImages.count {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imageCellId, for: indexPath) as! ImageCVCell
let userPickedImageObject = userPickedImages[item]
//cell.showImagesButton.setImage(userPickedImage, for: .normal)
cell.showImagesButton.setImage(userPickedImageObject.image, for: .normal)
cell.showImagesButton.addTarget(self, action: #selector(showAlreadyPickedImages), for: .touchUpInside)
//cell.addButton.addTarget(self, action: #selector(showAlreadyPickedImages), for: .touchUpInside)
return cell
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: addCellId, for: indexPath) as! ImagePickerButtonCVCell
cell.addButton.addTarget(self, action: #selector(showImagePickerController), for: .touchUpInside)
return cell
// Configure the cell
}
//Function shows imagePicker that helps in picking images and capturing images with camera
func showImagePickerController(){
print("showImagePickerController func called")
//self.present(imagePickerController, animated: true, completion: nil)
self.navigationController?.pushViewController(imagePickerController, animated: true)
}
func showAlreadyPickedImages(){
let vc = self.storyboard?.instantiateViewController(withIdentifier: "userPickedImagesVC") as! UserPickedImagesVC
//vc.contentImages = userPickedImages
vc.imageObjectsArray = userPickedImages
vc.showingAlreadySavedImages = true
self.navigationController?.pushViewController(vc, animated: true)
}
func setImagesInCells(imageObjects : [ImageObject]){
print("setImagesInCells func called in CVC")
userPickedImages += imageObjects
collectionView?.reloadData()
}
// MARK: - ImagePickerDelegate
func cancelButtonDidPress(_ imagePicker: ImagePickerController) {
imagePicker.dismiss(animated: true, completion: nil)
}
func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
guard images.count > 0 else { return }
let lightboxImages = images.map {
return LightboxImage(image: $0)
}
let lightbox = LightboxController(images: lightboxImages, startIndex: 0)
imagePicker.present(lightbox, animated: true, completion: nil)
}
func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
imagePicker.dismiss(animated: true, completion: nil)
let vc = storyboard?.instantiateViewController(withIdentifier: "userPickedImagesVC") as! UserPickedImagesVC
//vc.contentImages = images
vc.imageObjectsArray = convertImagesToImageObjects(images)
//self.present(vc, animated: true, completion: nil)
self.navigationController?.pushViewController(vc, animated: true)
}
func convertImagesToImageObjects(_ imagesArray : [UIImage]) -> [ImageObject]{
var imageObjects = [ImageObject]()
for image in imagesArray{
var imageObject = ImageObject()
imageObject.image = image
imageObject.imageDescription = ""
imageObjects.append(imageObject)
}
return imageObjects
}
}
UserPickedImagesVC.swift
import UIKit
protocol UserPickedImagesVCProtocol{
func setImagesInCells(imageObjects : [ImageObject])
}
class ImageObject : NSObject{
var imageDescription : String?
var image : UIImage?
}
class UserPickedImagesVC: UIViewController, UIPageViewControllerDataSource {
var pageViewController : UIPageViewController?
let placeholderText = "Image description.."
var imageObjectsArray = [ImageObject]()
var delegate : UserPickedImagesVCProtocol!
var showingAlreadySavedImages = false
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = [] // To avoid view going below nav bar
//self.delegate = self.navigationController?.viewControllers
// Do any additional setup after loading the view, typically from a nib.
if showingAlreadySavedImages{
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneTapped))
}else{
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(saveTapped))
}
// createImageAndDescriptionDict()
createPageViewController()
setupPageControl()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func createPageViewController(){
print("createPageViewController func called")
let pageController = self.storyboard?.instantiateViewController(withIdentifier: "userPickedImagesPageController") as! UIPageViewController
pageController.dataSource = self
if imageObjectsArray.count > 0 {
let firstController = getItemController(0)
let startingViewControllers = [firstController]
pageController.setViewControllers(startingViewControllers as! [UIViewController], direction: .forward, animated: false, completion: nil)
}
pageViewController = pageController
addChildViewController(pageViewController!)
self.view.addSubview((pageViewController?.view)!)
pageViewController?.didMove(toParentViewController: self)
}
// Creata the appearance of pagecontrol
func setupPageControl(){
let appearance = UIPageControl.appearance()
appearance.pageIndicatorTintColor = UIColor.gray
appearance.currentPageIndicatorTintColor = UIColor.white
appearance.backgroundColor = UIColor.darkGray
}
//MARK: Delagate methods
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let itemController = viewController as! UserPickedImageVC
if itemController.itemIndex > 0 {
return self.getItemController(itemController.itemIndex-1)
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let itemController = viewController as! UserPickedImageVC
if itemController.itemIndex + 1 < imageObjectsArray.count{
return getItemController(itemController.itemIndex+1)
}
return nil
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return imageObjectsArray.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return 0
}
func currentControllerIndex() -> Int{
let pageItemController = self.currentControllerIndex()
if let controller = pageItemController as? UserPickedImageVC{
return controller.itemIndex
}
return -1
}
func currentController() -> UIViewController?{
if(self.pageViewController?.viewControllers?.count)! > 0{
return self.pageViewController?.viewControllers?[0]
}
return nil
}
func getItemController(_ itemIndex:Int) -> UserPickedImageVC?{
if itemIndex < imageObjectsArray.count{
let pageItemController = self.storyboard?.instantiateViewController(withIdentifier: "userPickedImageVC") as! UserPickedImageVC
pageItemController.itemIndex = itemIndex
//pageItemController.imageName = imageObjectsArray[itemIndex]
//pageItemController.imageToShow = imageObjectsArray[itemIndex]
//pageItemController.imageToShow = getImageFromImageDescriptionArray(itemIndex, imagesAndDescriptionArray)
pageItemController.imageObject = imageObjectsArray[itemIndex]
pageItemController.itemIndex = itemIndex
pageItemController.showingAlreadySavedImage = showingAlreadySavedImages
print("Image Name from VC: \(imageObjectsArray[itemIndex])")
return pageItemController
}
return nil
}
// Passing images back to Collection View Controller when save button is tapped
func saveTapped(){
let viewControllers = self.navigationController?.viewControllers
//print("viewControllers: \(viewControllers)")
if let destinationVC = viewControllers?[0]{
self.delegate = destinationVC as! UserPickedImagesVCProtocol
//self.delegate.setImagesInCells(images : imageObjectsArray)
self.delegate.setImagesInCells(imageObjects : imageObjectsArray)
self.navigationController?.popToViewController(destinationVC, animated: true)
}
}
func doneTapped(){
let viewControllers = self.navigationController?.viewControllers
if let destinationVC = viewControllers?[0] {
self.navigationController?.popToViewController(destinationVC, animated: true)
}
}
}
UserPickedImageVC.swift
import UIKit
import ImageScrollView
extension UIViewController {
var className: String {
return NSStringFromClass(self.classForCoder).components(separatedBy: ".").last!;
}
}
class UserPickedImageVC: UIViewController, UITextViewDelegate {
var itemIndex : Int = 0
var imageDescription : String = ""
var imageScrollView = ImageScrollView()
var imageDescriptionTextView : UITextView!
var imageToShow : UIImage!
var imageObject : ImageObject?
var deleteButton = UIButton(type: .system)
var showingAlreadySavedImage = false
var pageViewController : UIPageViewController!
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = [] // To avoid images going below the navigation bars
pageViewController = self.parent as! UIPageViewController
setConstraints()
setImageAndDescription()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: TextView delegate methods
func textViewDidBeginEditing(_ textView: UITextView)
{
if (imageDescriptionTextView.text == "Image description..")
{
imageDescriptionTextView.text = ""
imageDescriptionTextView.textColor = .black
}
imageDescriptionTextView.becomeFirstResponder() //Optional
}
func textViewDidEndEditing(_ textView: UITextView)
{
let imageDescription = imageDescriptionTextView.text
if (imageDescription == "")
{
imageDescriptionTextView.text = "Image description.."
imageDescriptionTextView.textColor = .lightGray
}
imageObject?.imageDescription = imageDescription
updateImageObject(imageObject!)
imageDescriptionTextView.resignFirstResponder()
}
//MARK: Private Methods
func setImageAndDescription(){
if let imageToDisplay = imageObject?.image{
imageScrollView.display(image: imageToDisplay) // Setting Image
}
imageDescriptionTextView.text = imageObject?.imageDescription // Setting Description
}
// Function to update imageObject in UserPickedImagesVC
func updateImageObject(_ imageObject: ImageObject){
guard let controllers = self.navigationController?.viewControllers else{
return
}
for viewController in controllers {
if viewController.className == "UserPickedImagesVC" {
let vc = viewController as! UserPickedImagesVC
vc.imageObjectsArray[itemIndex] = imageObject
}
}
}
// Function to delete imageObject from UserPickedImagesVC
func deleteCurrentImageObject(){
guard let controllers = self.navigationController?.viewControllers else{
return
}
for viewController in controllers {
if viewController.className == "UserPickedImagesVC"{
let vc = viewController as! UserPickedImagesVC
let objectCount = vc.imageObjectsArray.count
guard objectCount > 0 && objectCount >= itemIndex else {
return
}
vc.imageObjectsArray.remove(at: itemIndex) // Removing imageObject from the array
if let pageVC = vc.childViewControllers[0] as? UIPageViewController {
pageVC.setViewControllers([], direction: .forward, animated: true, completion: nil)
}
}
}
}
func showOrHideDeleteButton(){
if showingAlreadySavedImage{
print("deleteButton.isNotHidden")
deleteButton.isHidden = false
}else{
print("deleteButton.isHidden")
deleteButton.isHidden = true
}
}
func setConstraints(){
let viewSize = self.view.frame.size
let viewWidth = viewSize.width
let viewHeight = viewSize.height
print("viewWidth: \(viewWidth), viewHeight: \(viewHeight)")
view.addSubview(imageScrollView)
imageScrollView.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight)
deleteButton.tintColor = Colors.iOSBlue
deleteButton.setImage(#imageLiteral(resourceName: "delete"), for: .normal)
deleteButton.backgroundColor = Colors.white
deleteButton.layer.cornerRadius = 25
deleteButton.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
//deleteButton.currentImage.
deleteButton.imageView?.tintColor = Colors.iOSBlue
deleteButton.addTarget(self, action: #selector(deleteCurrentImageObject), for: .touchUpInside)
deleteButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(deleteButton)
showOrHideDeleteButton()
imageDescriptionTextView = UITextView()
imageDescriptionTextView.delegate = self as! UITextViewDelegate
imageDescriptionTextView.text = "Image description.."
imageDescriptionTextView.textColor = .lightGray
//imageScrollView.clipsToBounds = true
imageDescriptionTextView.translatesAutoresizingMaskIntoConstraints = false
//imageDescriptionTextView.backgroundColor = UIColor.white.withAlphaComponent(0.8)
imageDescriptionTextView.backgroundColor = UIColor.white
imageDescriptionTextView.layer.cornerRadius = 5
imageDescriptionTextView.layer.borderColor = UIColor.lightGray.cgColor
imageDescriptionTextView.layer.borderWidth = 0.5
view.addSubview(imageDescriptionTextView)
let viewsDict = [
"imageDescriptionTextView" : imageDescriptionTextView,
"deleteButton" : deleteButton
] as [String:Any]
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-5-[imageDescriptionTextView]-70-|", options: [], metrics: nil, views: viewsDict))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[imageDescriptionTextView(50)]-5-|", options: [], metrics: nil, views: viewsDict))
imageDescriptionTextView.sizeThatFits(CGSize(width: imageDescriptionTextView.frame.size.width, height: imageDescriptionTextView.frame.size.height))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[deleteButton(50)]-5-|", options: [], metrics: nil, views: viewsDict))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[deleteButton(50)]-5-|", options: [], metrics: nil, views: viewsDict))
}
}
create a call back property in UserPickedImageVC.swift
typealias DeleteCallBack = (int) -> Void
...
var itemIndex : Int = 0
var deleteCallBack:DeleteCallBack?
...
func deleteCurrentImageObject(){
self.deleteCallBack?(self.itemIndex)
}
in UserPickedImagesVC.swift
func getItemController(_ itemIndex:Int) -> UserPickedImageVC?{
if itemIndex < imageObjectsArray.count{
let pageItemController = self.storyboard?.instantiateViewController(withIdentifier: "userPickedImageVC") as! UserPickedImageVC
pageItemController.itemIndex = itemIndex
pageItemController.imageObject = imageObjectsArray[itemIndex]
pageItemController.itemIndex = itemIndex
pageItemController.showingAlreadySavedImage = showingAlreadySavedImages
print("Image Name from VC: \(imageObjectsArray[itemIndex])")
pageItemController.deleteCallBack = {
[weak self] (index) -> Void in
self?.deleteItemAt(index: index)
}
return pageItemController
}
return nil
}
func deleteItemAt(index: Int) {
if (imageObjectsArray.count > 1) {
imageObjectsArray.remove(at: itemIndex)
self.pageViewController.dataSource = nil;
self.pageViewController.dataSource = self;
let firstController = getItemController(0)
let startingViewControllers = [firstController]
pageViewController.setViewControllers(startingViewControllers as! [UIViewController], direction: .forward, animated: false, completion: nil)
} else {
//redirect here
_ = navigationController?.popViewController(animated: true)
}
}

UIImageViews / Adding Multiple Stickers To A View.

Intro:
Functionality of adding multiple stickers/emoji to a view.
Setup:
There are 2 view controllers - one to which we're adding stickers, and another with a collectionview of stickers.
Stickers themselves are passed in arrays in 'prepareForSegue' func.
There are 2 arrays, one with just sticker images, another - with UIImageViews - stickers that were already panned, pinched and rotated.
Bug:
After adding 2nd sticker, the AddingStickersVC reappears but previous sticker isn't where we left if. It is pinched and zoomed, but not panned. Also new stickers are sticked to the first one (same frame?).
We can pinch and zoom previous stickers separately from new ones - (nope, they have their own frames), but we can't separate them.
End up having a stack of UIImageViews that takes rotating and pinching separately but pans all together.
Also, speed of panning is increasing after each additional sticker (the panning gesture is added multiple time?).
Hierarchy of views
Stickers are added to 'viewForEmoji' view (viewForImgAndEmoji).
AddingStickersVC:
#IBOutlet weak var viewForImgAndEmoji: UIView!
#IBOutlet weak var mainImg: UIImageView!
#IBOutlet weak var viewForSnapshot: UIView!
var imageData: Data!
var imageItself: UIImage!
var currentUserPostRef: FIRDatabaseReference!
var emojiImage: UIImage!
var geoFire: GeoFire!
var arrayOfEmojis = [UIImage]()
var arrayOfEmojiViews = [UIImageView]()
var n:Int = 1
override func viewDidLoad() {
super.viewDidLoad()
if imageData != nil {
let img = UIImage(data: imageData)
let fixedImg = img!.fixOrientation(img: img!)
mainImg.image = fixedImg
} else if imageItself != nil {
mainImg.image = imageItself
}
if arrayOfEmojiViews.count != 0 {
for emojiView1 in arrayOfEmojiViews {
viewForImgAndEmoji.addSubview(emojiView1)
}
}
// get image out of array.
if arrayOfEmojis.count != 0 {
for emoji in arrayOfEmojis {
let emojiView = UIImageView(image: emoji)
emojiView.tag = n
emojiView.frame = CGRect(x: 153, y: 299, width: 70, height: 70)
emojiView.isUserInteractionEnabled = true
let pan = UIPanGestureRecognizer(target: self, action: #selector(self.handlePan(recognizer:)))
pan.delegate = self
viewForImgAndEmoji.addGestureRecognizer(pan)
let pinch = UIPinchGestureRecognizer(target: self, action: #selector(self.handlePinch(recognizer:)))
pinch.delegate = self
viewForImgAndEmoji.addGestureRecognizer(pinch)
let rotate = UIRotationGestureRecognizer(target: self, action: #selector(self.handleRotate(recognizer:)))
rotate.delegate = self
viewForImgAndEmoji.addGestureRecognizer(rotate)
// check so we won't add previous emoji. only new.
if viewForImgAndEmoji.viewWithTag(n) == nil {
viewForImgAndEmoji.addSubview(emojiView)
}
n += 1
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if arrayOfEmojis.count != 0 {
for j in 1...n {
if var view1 = self.viewForImgAndEmoji.viewWithTag(j) as? UIImageView {
arrayOfEmojiViews.append(view1)
print("Zhenya: views frame is \(view1.frame)")
}
}
}
if segue.identifier == "EmojiCollectionVC" {
if let emojiCollection = segue.destination as? EmojiCollectionVC{
if let image = sender as? UIImage {
emojiCollection.userImage = image
if arrayOfEmojis.count != 0 {
//arrayToStoreEmojis
emojiCollection.arrayToStoreEmojis = arrayOfEmojis
emojiCollection.arrayToStoreEmojiViews = arrayOfEmojiViews
}
}
}
}
}
#IBAction func handlePan(recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.viewForImgAndEmoji)
if let view = recognizer.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
recognizer.setTranslation(CGPoint.zero, in: self.viewForImgAndEmoji)
}
#IBAction func handlePinch(recognizer: UIPinchGestureRecognizer) {
let pinchPoint = recognizer.location(in: viewForImgAndEmoji)
let ourEmojiView = viewForImgAndEmoji.hitTest(pinchPoint, with: nil)
ourEmojiView!.transform = ourEmojiView!.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
recognizer.scale = 1
}
#IBAction func handleRotate(recognizer: UIRotationGestureRecognizer){
let rotatePoint = recognizer.location(in: viewForImgAndEmoji)
let ourEmojiView = viewForImgAndEmoji.hitTest(rotatePoint, with: nil)
ourEmojiView!.transform = ourEmojiView!.transform.rotated(by: recognizer.rotation)
recognizer.rotation = 0
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
And EmojiCollectionVC:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! EmojiCollectionCell
let chosenEmoji = cell.emojiView.image as UIImage!
arrayToStoreEmojis.append(chosenEmoji!)
performSegue(withIdentifier: "backToEmojiVC", sender: arrayToStoreEmojis)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "backToEmojiVC"{
if let destinationVC = segue.destination as? EmojiVC {
if let array = sender as? [UIImage] {
destinationVC.arrayOfEmojis = arrayToStoreEmojis
destinationVC.arrayOfEmojiViews = arrayToStoreEmojiViews
let data = UIImagePNGRepresentation(userImage)
destinationVC.imageData = data
}
}
}
}
Found solution.
There reason why all new imageViews were stacked - because after panning imageViews didn't change their location in view. The whole f view was moving.
(to find this, spent 8hours tracking changes of frame origins with 'prints' at every step of the program).
And the reason the whole view was moving - because panning gesture was added to the whole view.
So instead of
let pan = UIPanGestureRecognizer(target: self, action: #selector(self.handlePan(recognizer:)))
pan.delegate = self
viewForImgAndEmoji.addGestureRecognizer(pan)
i needed:
let pan = UIPanGestureRecognizer(target: self, action: #selector(self.handlePan(recognizer:)))
pan.delegate = self
emojiView.addGestureRecognizer(pan)
What is interesting, for pinching and rotating - we still add them to the whole view that contains emojiView:
viewForImgAndEmoji.addGestureRecognizer(pinch)
...
viewForImgAndEmoji.addGestureRecognizer(rotate)

Resources