prepareForSegue sending data to tableview in a container view - ios

I am sending data from one tableview list to another tableview used as a detail view for the selected cell. Simple -
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
let index = tableView.indexPathForSelectedRow
if (segue.identifier == "EventDetailSegue") {
let detailVC = segue.destinationViewController as! EventDetailTableViewController
var event : Event
if searchController.active && searchController.searchBar.text != "" {
event = filteredEvents[index!.row]
} else {
event = events[index!.row]
}
detailVC.eventImage = event.image
detailVC.eventCompany = event.company
detailVC.eventName = event.name
detailVC.eventLocation = event.location
detailVC.eventPrice = event.price
detailVC.eventPromoterImage = event.promoterImage
}
}
Since I now want to have a static button bar on the bottom of the detail tableview. I need to change the EventDetailTableViewController to be in a container view on a UIViewController. So I can then simply do what I want inside the UIViewController.
My question is how do I still send this data to the now embedded EventDetailTableViewController inside the container view? Since the segue will now need to be going to the UIViewController with the container view, but I also need to make sure this data is passed to that TableView inside the container.

i use color instead of data :
EventDetailTableViewController ->ViewController3
UIViewController -> ViewController2
try like this :
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let tableVc = ViewController3()
tableVc.color = UIColor.redColor()
let vc = ViewController2()
vc.tableViewController = tableVc
self.navigationController?.pushViewController(vc, animated: true)
}
}
class ViewController2: UIViewController {
var tableViewController:ViewController3!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.yellowColor()
tableViewController.willMoveToParentViewController(self)
addChildViewController(tableViewController)
tableViewController.view.frame = CGRect(x: 0, y: 100, width: 100, height: 100)
view.addSubview(tableViewController.view)
tableViewController.didMoveToParentViewController(self)
}
}
class ViewController3: UITableViewController {
var color :UIColor!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = color
}
}
hope it be helpful :-)

Related

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

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
}
}

UIScrollView not recognising ShakeGesture

ScrollView is not recognising shake gesture
I have 3 files.
1.ContentVC - consists of scrollView to swipe between viewcontrollers
2.FirstVC - It contains shakegesture function
3.SecondVC - default view controller
When i shake the device nothing happens.
ContentVC.swift
class ContainerVC: UIViewController {
#IBOutlet weak var scroll: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
let left = self.storyboard?.instantiateViewController(withIdentifier: "vw") as! UINavigationController
self.addChild(left)
self.scroll.addSubview(left.view)
self.didMove(toParent: self)
let last = self.storyboard?.instantiateViewController(withIdentifier: "lastviewNav") as! UINavigationController
self.addChild(last)
self.scroll.addSubview(last.view)
self.didMove(toParent: self)
var middleframe:CGRect = last.view.frame
middleframe.origin.x = self.view.frame.width
last.view.frame = middleframe
self.scroll.contentSize = CGSize(width: (self.view.frame.width) * 2, height: (self.view.frame.height))
}
}
FirstVC.swift
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if event?.subtype == UIEvent.EventSubtype.motionShake {
if motion == .motionShake {
print("quote is appearing by shaking the device")
} else {
print("No quote is coming")
}
}
}
Motion events are delivered initially to the first responder and are forwarded up the responder chain as appropriate.
https://developer.apple.com/documentation/uikit/uiresponder/1621090-motionended
So make sure that:
FirstVC able to became first responder:
override var canBecomeFirstResponder: Bool {
return true
}
FirstVC is first responder at specific point of time:
firstVC.becomeFirstResponder()
Now your UIViewController will be able to receive shake motion events.
You can read more about Responder chain: How do Responder Chain Works in IPhone? What are the "next responders"?

How to access UIView in ViewController when calling function from another file?

Situation: I paint stuff through a button-click on a subview. Then I add the subview to the view.
Problem: When calling drawNew from another swift file, the if-loop is not triggered. Probably because the view with the tag 777 does not get found.
Question: How do I tell the code to look for the view in ViewController?
When do I call the function drawNew()? I call it from another file with override func touchesEnded(...)
//###########################
// ViewController.swift
//###########################
var dv = Painting() // in here are functions to create a cg path
//
// IBActions
//
#IBAction func buttonPressed(_ sender: UIButton) {
// painting
if sender.tag == 1 {
drawNew()
} else if sender.tag == 2 {
CanvasView.clearCanvas()
}
}
//
// FUNCTIONS
//
func drawNew() {
dv.makeMeSomePath()
if let foundView = view.viewWithTag(777) { // problem lies here maybe
dv.tag = 111
foundView.addSubview(dv)
print("added subview")
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// prepare the canvas for
let newView = CharacterView(frame: CGRect(x: 0,
y:0,
width: HandwritingCanvasView.frame.width,
height: HandwritingCanvasView.frame.height))
newView.tag = 777
HandwritingCanvasView.addSubview(newView)
// self.view.addSubview(demoView)
}
Then this is the other file from where I call the drawNew() func
// HandwritingCanvasView.swift
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
ViewController.drawNew()
}
It will be easier to have reference on newView in ViewController.
Try to do next
//###########################
// ViewController.swift
//###########################
weak var subView: UIView? //Add reference on your view
//
// FUNCTIONS
//
func drawNew() {
dv.makeMeSomePath()
if let foundView = subView { // Use the reference instead of searching view with tag
dv.tag = 111
foundView.addSubview(dv)
print("added subview")
}
}
override func viewDidAppear(_ animated: Bool) {
// Your code is here
// ...
HandwritingCanvasView.addSubview(newView)
subView = newView
//...
}

Load different images based on text label in TableView

I have a Table View with basic label of Table View Cell. I labelled the cell as "January", "February", "March", etc. When user tap on "January", an image with file name "jan.jpeg" will be showed using the following Swift code:
override func viewDidLoad() {
super.viewDidLoad()
let image = UIImage(named: "jan.jpeg")!
imageView = UIImageView(image: image)
imageView.frame = CGRect(origin: CGPointMake(0.0, 0.0), size:image.size)
}
My question is, is it possible when user tap on "February", "feb.jpeg" will be showed, whereas "mar.jpeg will be showed if user tap on "Mar"? How to implement this?
When a cell is selected, the tableView:didSelectRowAtIndexPath: delegate method is called. If you have a predefined list of cells, you can test which cell is being tapped and load the correct image. For example:
have a variable var imgName: String outside of all functions in the viewcontroller with your tableView.
Also put this function in the viewcontroller with your tableView:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 0 {
imgName = "jan.jpeg"
}
else if indexPath.row == 1 {
imgName = "feb.jpeg"
}
else if indexPath.row == 2 {
imgName = "mar.jpeg"
}
else {
// Handle else
}
self.performSegueWithIdentifier("showImageSegue", sender: self)
}
You will need to go to interface builder and name the segue between your viewcontrollers to "showImageSegue".
Additionally, implement the prepareForSegue: function:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
let destinationVC = segue.destinationViewController as ImageViewController // Replace ImageViewController with whatever the name of your destination viewcontroller is.
destinationVC.imageName = imgName
}
Finally, inside the ImageViewController class, add this:
var imageName: String
override func viewDidLoad() {
let image = UIImage(named: imageName)
imageView = UIImageView(image: image)
imageView.frame = CGRect(origin: CGPointMake(0,0, 0,0), size: image.size)
}

Disable UIPageViewController bouncing - Swift [duplicate]

This question already has answers here:
Disable UIPageViewController bounce
(16 answers)
Closed 5 years ago.
I've been making a sample app with scrolling between UIViewControllers but the point is i want to disable the bouncing effect at the end of scrolling and when going back to the first UIViewController.
here is my code :
class PageViewController: UIPageViewController,UIPageViewControllerDataSource, UIPageViewControllerDelegate{
var index = 0
var identifiers: NSArray = ["FirstNavigationController", "SecondNavigationController"]
override func viewDidLoad() {
self.dataSource = self
self.delegate = self
let startingViewController = self.viewControllerAtIndex(self.index)
let viewControllers: NSArray = [startingViewController]
self.setViewControllers(viewControllers as [AnyObject], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
}
func viewControllerAtIndex(index: Int) -> UINavigationController! {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
//first view controller = firstViewControllers navigation controller
if index == 0 {
return storyBoard.instantiateViewControllerWithIdentifier("FirstNavigationController") as! UINavigationController
}
//second view controller = secondViewController's navigation controller
if index == 1 {
return storyBoard.instantiateViewControllerWithIdentifier("SecondNavigationController") as! UINavigationController
}
return nil
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
let identifier = viewController.restorationIdentifier
let index = self.identifiers.indexOfObject(identifier!)
//if the index is the end of the array, return nil since we dont want a view controller after the last one
if index == identifiers.count - 1 {
return nil
}
//increment the index to get the viewController after the current index
self.index = self.index + 1
return self.viewControllerAtIndex(self.index)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
let identifier = viewController.restorationIdentifier
let index = self.identifiers.indexOfObject(identifier!)
//if the index is 0, return nil since we dont want a view controller before the first one
if index == 0 {
return nil
}
//decrement the index to get the viewController before the current one
self.index = self.index - 1
return self.viewControllerAtIndex(self.index)
}
}
Take a look here :
I don't know if you can. UIPageController is not very customizable.
Personally, when I want to scroll between UIViewController, I prefer using a simple UIViewController, which will be a container, with an UIScrollView in it. Then I add programmatically all the controllers in the contentSize of the UIScrollView. You have to add all the controllers as child of the container.
UPDATE iOS 9
func setupDetailViewControllers() {
var previousController: UIViewController?
for controller in self.controllers {
addChildViewController(controller)
addControllerInContentView(controller, previousController: previousController)
controller.didMoveToParentViewController(self)
previousController = controller
}
}
func addControllerInContentView(controller: UIViewController, previousController: UIViewController?) {
contentView.addSubview(controller.view)
controller.view.translatesAutoresizingMaskIntoConstraints = false
// top
controller.view.topAnchor.constraintEqualToAnchor(contentView.topAnchor).active = true
// bottom
controller.view.bottomAnchor.constraintEqualToAnchor(contentView.bottomAnchor).active = true
// trailing
trailingContentViewConstraint?.active = false
trailingContentViewConstraint = controller.view.trailingAnchor.constraintEqualToAnchor(contentView.trailingAnchor)
trailingContentViewConstraint?.active = true
// leading
let leadingAnchor = previousController?.view.trailingAnchor ?? contentView.leadingAnchor
controller.view.leadingAnchor.constraintEqualToAnchor(leadingAnchor).active = true
// width
controller.view.widthAnchor.constraintEqualToAnchor(scrollView.widthAnchor).active = true
}
PREVIOUS ANSWER
Like so :
scrollView is an IBOutlet with contraints to each edge of the ContainerViewController
class ContainerViewController: UIViewController {
#IBOutlet var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.bounces = false
scrollView.pagingEnabled = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidLayoutSubviews() {
initScrollView()
}
func initScrollView(){
let viewController1 = storyboard?.instantiateViewControllerWithIdentifier("ViewController1") as! ViewController1
viewController1.willMoveToParentViewController(self)
viewController1.view.frame = scrollView.bounds
let viewController2 = storyboard?.instantiateViewControllerWithIdentifier("ViewController2") as! ViewController2
viewController2.willMoveToParentViewController(self)
viewController2.view.frame.size = scrollView.frame.size
viewController2.view.frame.origin = CGPoint(x: view.frame.width, y: 0)
scrollView.contentSize = CGSize(width: 2 * scrollView.frame.width, height: scrollView.frame.height)
scrollView.addSubview(viewController2.view)
self.addChildViewController(viewController2)
viewController2.didMoveToParentViewController(self)
scrollView.addSubview(viewController1.view)
self.addChildViewController(viewController1)
viewController1.didMoveToParentViewController(self)
}}

Resources