Empty a UIPageViewController (remove ViewControllers inside) - ios

How can I remove all the viewControllers inside a UIPageViewController in Swift?
Those calls:
pageViewController.setViewControllers(nil,....)
pageViewController.setViewControllers([UIViewController(),....)
both make my app crash with the following message:The number of view controllers provided (0) doesn't match the number required (1) for the requested transition

A UIPageViewController does not "hold view controllers" in the sense you are thinking of. All it does is display a view controller returned by its dataSource ... and its dataSource is your code.
If you simply do this:
[pageViewController setViewControllers:#[UIViewController.new] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
That will replace the current "page" with an empty UIViewController - but it won't do anything else. You'll still be able to scroll, and depending on your next/previous logic, that may result in other errors.
What you'll want to do is "clear" the current page with that line, but then also prevent scrolling / swiping. This is often done by setting the UIPageViewController's dataSource to nil.

What Don explained, for 2020:
As #DonMag has explained. Really all you can do is
Simply replace the current VC you are seeing, with, a blank one.
Set the datasource of the page view controller to null
Important caveats ..
• What does it really mean to have a "blank" VC in your app? It could be, you make as special view controller (which is just "gray clouds" or "an explanation that there is no data" or something) which you use.
• But you can in fact safely just use UIViewController() and it will be blank, nothingness.
• With point 2, don't forget to set it back!
In practice... something like...
var vcs: [UIViewController] = []
func reloadPages() {
print("reload pages in your page view controller")
let k = yourData.count
if k == 0 {
dataSource = nil
setViewControllers([UIViewController()], direction: .forward, animated: false)
return
}
dataSource = self
vcs = []
for i in 0..<k {
let vc = _sb("SomePageOfYours") as! SomePageOfYours
vcs.append(vc)
}
setViewControllers([vcs[0]], direction: .forward, animated: false)
}
In the last line of code, don't forget it's an array of only the first item, not the whole array.
Aside - the call '_sb' is just something that loads your view controller from it's storyboard. Example,
func _sb(_ s: String) -> UIViewController {
// assume the storyboard id is set as ClassNameID
return UIStoryboard(name: s, bundle: nil)
.instantiateViewController(withIdentifier: s + "ID")
}

Related

Close a viewcontroller after a segue

What I want is to close a viewController after performing a segue so that the back button of the navigation controller on the new view doesn't go back to the view that I just closed, but it goes to the view that precedes it in the storyboard like it is the first time that it is loaded.
I already tried stuff like dismiss and so but it doesn't really work for me as it only closes the view in which the button that I pressed for performing the function is located :
#objc func goToList(){
self.dismiss(animated: true, completion: nil)
performSegue(withIdentifier: "goToList", sender: nil)
}
The navigation controller maintains a stack (array) of ViewControllers that have been opened (pushed). It also has the ability to pop these ViewControllers off the stack until it gets to a specific one.
For example, if you wished to return to a previous view controller of type MyInitialVC then you'd want to search through the stack until you found that type of VC, and then pop to it:
let targetVC = navigationController?.viewControllers.first(where: {$0 is MyInitialVC})
if let targetVC = targetVC {
navigationController?.popToViewController(targetVC, animated: true)
}
NB. written from memory without XCode, so you may need to correct minor typos
You can use unwind segue to get back to each viewController that you want.
Read more here:
Unwind Segues Step-by-Step (and 4 Reasons to Use Them)

Detect that from which Page I come to the current Page

I want to know how to do this:
I have 3 view controllers and the first and second view controller are connected to the third one !
I want to know how can I write a code that detect from which one I came to this view controller
I have searched here for my answer But all of the similar questions asked about navigation !!!
The Important thing is that I don't have navigation in my app!!
I don't know if my answer will help you in your specific case, but here is the implementation I see from what you are asking. Maybe it will inspire you.
So imagine your are in your homePage or whatever viewController and you want to navigate throw other, but you want to know from which viewController you came from.
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:segue_VC1]) {
CustomViewController1* destinationVC = segue.destinationViewController;
destinationVC.fromSegue = #"I AM VC 1";
}
if ([segue.identifier isEqualToString:segue_VC2]) {
CustomViewController2* destinationVC = segue.destinationViewController;
destinationVC.fromSegue = #"I AM VC 2";
}
}
The more important thing you have to know is that you can access attribute from the destination view controller you will access with your segue.
I know this is in Obj C, but the implementation is still the same.
So that when you navigate from a ViewController to an other one, you can set the attribute of the destinationViewController.
Then when you are in the view controller you wanted to navigate you can check :
if ([_fromSegue isEqualToString: "I AM VC 1"])
// do specific stuff when you come from VC 1
else if ([_fromSegue isEqualToString: "I AM VC 2"])
// do specific stuff when you come from VC 2
else
// other case
There are many ways to do that like simply passing a view controller as a property to the new instance. But in your case it might make more sense to create a static variable which holds the stack of the view controllers the same way the navigation controller does that.
If you are doing this only between the UIViewController subclasses I suggest you to create another subclass of it form which all other view controllers inherit. Let us call it TrackedViewController.
class TrackedViewController : UIViewController {
static var currentViewController: TrackedViewController?
static var previousViewController: TrackedViewController?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
TrackedViewController.previousViewController = TrackedViewController.currentViewController
TrackedViewController.currentViewController = self
}
}
Now you need to change all the view controllers you want to track so that they all inherit from TrackedViewController as class MyViewController : TrackedViewController {. And that is pretty much it. Now at any point anywhere in your project you can find your current view controller via TrackedViewController.currentViewController and the previous view controller via TrackedViewController.previousViewController. So you can say something like:
if let myController = TrackedViewController.previousViewController as? MyViewController {
// Code here if the screen was reached from MyViewController instance
}
Now the way I did it was through the instance of the view controller which may have some side effects.
The biggest problem you may have is that the previous controller is being retained along with the current view controller. That means you may have 2 controllers in memory you do not need.
If you go from controller A to B to C and back to B then the previous view controller is C, not A. This might be desired result or not.
The system will ignore all other view controllers. So if you use one that is not a subclass of TrackedViewController the call will be ignored: A to B to UITableViewController to C will report that the C was presented by B even though there was another screen in between. Again this might be expected result.
So if the point 2 and 3 are good to you then you should only decide weather to fix the point 1. You may use weak to remove the retaining on the two properties but then you lose the information of the previous view controller if the controller is deallocated. So another choice is to use some identifiers:
class TrackedViewController : UIViewController {
static var currentViewControllerID: String?
static var previousViewControllerID: String?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
TrackedViewController.previousViewControllerID = TrackedViewController.currentViewControllerID
TrackedViewController.currentViewControllerID = self.screenIdentifier
}
var screenIdentifier: String {
return "Default Screen" // TODO: every view controller must override this method and have unique identifier
}
}
Also you may replace strings with some enumeration or something. Combining them with some associated values could then create quite a powerful tool.

Progress bar crashes when updated from swift file that is not it's viewController

I have a file in Swift that holds all my queries. And when saving a record with saveOperation.perRecordProgressBlock this file call ChatView view controller and updates the progressBarUpdate function.
So far I can get the print within progressBarUpdate to print the progress just fine. But when I get to update progressBarMessage.setProgress(value!, animated: true) the application just crash with the following error: fatal error: unexpectedly found nil while unwrapping an Optional value
If I try to run progressBarMessage.setProgress(value!, animated: true) through viewDidLoad it updates the progress bar fine, no error. Which means the outlet is working just fine.
Other thing to consider, is that my print(".... perRecordProgressBlock - CHAT VIEW\(value)") works just fine. If gets the updates from Queris.swift. It is just the progressBarUpdate that is causing issues.
# my Queries.swift file option 1
saveOperation.perRecordProgressBlock = { (recordID, progress) -> Void in
print("... perRecordProgressBlock \(Float(progress))")
var chatView = ChatView()
chatView.progressBarUpdate(Float(progress))
}
# my Queries.swift file option 2
saveOperation.perRecordProgressBlock = { (recordID, progress) -> Void in
print("... perRecordProgressBlock \(Float(progress))")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let chatViewController = storyboard.instantiateViewControllerWithIdentifier("ChatViewVC") as! ChatView
chatViewController.progressBarUpdate(Float(progress))
}
# ChatView view controller
func progressBarUpdate(value: Float)
{
print(".... perRecordProgressBlock - CHAT VIEW\(value)")
if (value as? Float) != nil
{
progressBarMessage.setProgress(value, animated: true)
}
}
The way you are instantiating the viewController is not the right way and hence the crash/nil val. viewController loads its view hierarchy only when something sends it a view message. The system will do this by its own when to put the view hierarchy on the screen. And it happens after calls like prepareForSegue:sender: and viewWillAppear: , loadView(), self.view.
So here your outlets are still nil since it is not loaded yet.
Just try to force your viewController to call self.view and then access the functions from that viewController.
var chatView = ChatView()
I'm going to go out on a limb here and say you are using storyboards/xibs. If so, the above would not be the correct way to instantiate a new view controller. Here's some information on the difference (the question refers to Objective-C but the concept is the same in Swift)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let chatViewController = storyboard.instantiateViewControllerWithIdentifier("identifier-you-set-in-storyboard") as! ChatView
Where identifier-you-set-in-storyboard is set in the interface builder (the linked question is old but illustrates the concept, the field label might have changed in newer versions)
If by some off chance you are creating you are setting up your views in code (as opposed to storyboards), you'd need to call chatView.loadView() before chatView.progressBarUpdate.... (Or just try to access the view property and it should call loadView for you.)

Presenting View Controller loses subviews when dismissing presented VC

I'm having some trouble playing around with two viewcontrollers that interact in a straightforward manner:
The homeViewController shows a to-do list, with an addTask button.
The addTask button will launch an additional viewController that acts as a "form" for the user to fill.
However, upon calling
self.dismissViewControllerAnimated(true, completion: nil);
inside the presented view controller I return to my home page, but it's blank white and it seems nothing can be seen except the highest-level view on the storyboard can be seen (i.e. the one that covers the entire screen).
All of my views, scenes, etc. were set up with autolayout in storyboard. I've looked around on Stack Overflow, which lead to me playing around with the auto-resizing subview parameter i.e.:
self.view.autoresizesSubviews = false;
to no avail. I'm either fixing the auto-resizing parameter wrong (in the wrong view of interest, or simply setting it wrong), or having some other problem.
Thanks in advance
edit:
I present the VC as follows:
func initAddNewTaskController(){
let addNewTaskVC = self.storyboard?.instantiateViewControllerWithIdentifier("AddNewTaskViewController") as! AddNewTaskViewController;
self.presentViewController(addNewTaskVC, animated: true, completion: nil);
}
edit2:
While I accept that using delegates or unwinding segue can indeed circumvent the problem I'm encountering (as campbell_souped suggests), I still don't understand what's fundamentally happening when I dismiss my view controller that causes a blank screen.
I understand that calling dismissViewControllerAnimated is passed onto the presenting view controller (in this case my homeViewController). Since I don't need to do any pre or post-dismissal configurations, the use of a delegate is (in my opinion) unnecessary here.
My current thought is that for some reason, when I invoke
dismissViewControllerAnimated(true, completion:nil);
in my addNewTaskViewController, it is actually releasing my homeViewController. I'm hoping someone can enlighten me regarding what it is exactly that I'm not understanding about how view controllers are presented/dismissed.
In a situation like this, I usually take one of two routes. Either set up a delegate on AddNewTaskViewController, or use an unwind segue.
With the delegate approach, set up a protocol:
protocol AddNewTaskViewControllerDelegate {
func didDismissNewTaskViewControllerWithSuccess(success: Bool)
}
Add an optional property that represents the delegate in your AddNewTaskViewController
var delegate: AddNewTaskViewControllerDelegate?
Then invoke the didDismissNewTaskViewControllerWithSuccess whenever you are about to dismiss AddNewTaskViewController:
If the record was added successfully:
self.delegate?.didDismissNewTaskViewControllerWithSuccess(true)
self.dismissViewControllerAnimated(true, completion: nil);
Or if there was a cancelation/ failure:
self.delegate?.didDismissNewTaskViewControllerWithSuccess(false)
self.dismissViewControllerAnimated(true, completion: nil);
Finally, set yourself as the delegate, modifying your previous snippet:
func initAddNewTaskController(){
let addNewTaskVC = self.storyboard?.instantiateViewControllerWithIdentifier("AddNewTaskViewController") as! AddNewTaskViewController;
self.presentViewController(addNewTaskVC, animated: true, completion: nil);
}
to this:
func initAddNewTaskController() {
guard let addNewTaskVC = self.storyboard?.instantiateViewControllerWithIdentifier("AddNewTaskViewController") as AddNewTaskViewController else { return }
addNewTaskVC.delegate = self
self.presentViewController(addNewTaskVC, animated: true, completion: nil);
}
...
}
// MARK: AddNewTaskViewControllerDelegate
extension homeViewController: AddNewTaskViewControllerDelegate {
func didDismissNewTaskViewControllerWithSuccess(success: Bool) {
if success {
self.tableView.reloadData()
}
}
}
[ Where the extension is outside of your homeViewController class ]
With the unwind segue approach, take a look at this Ray Wenderlich example:
http://www.raywenderlich.com/113394/storyboards-tutorial-in-ios-9-part-2
This approach involves Ctrl-dragging from your IBAction to the exit object above the view controller and then picking the correct action name from the popup menu

How to update UIPageViewController's page control count

I have a UIPageViewController with a page control. In the delegate, I implement the following methods:
presentationCountForPageViewController:
presentationIndexForPageViewController:
This works well, but the total number of pages can change, and the number of dots displayed in the page control doesn't change in this case.
How do I tell the page view controller to call presentationCountForPageViewController: to update the total number of dots when this happens?
So it turns out this was a result of using NSFetchedResultsController as the source of the data for pages. The count for NSFetchedResultsController was not getting updated before I called setViewControllers:direction:animated:completion: on the UIPageViewController.
The fix was to call the following function in controllerDidChangeContent: to force an update to the page control.
func refreshPageController() {
let controllers = pageController.viewControllers
if controllers.count > 0 {
pageController.setViewControllers(controllers, direction: .Forward, animated: false, completion: nil)
}
}
Update:
Though the solution above worked, it broke the animation I was using to scroll to the next page when a page was removed.
A better solution: just wait until the page removal is committed to Core Data before calling setViewControllers:direction:animated:completion:.
I had the same problem, and the workaround I found is to reset the uipageviewcontroller view every time I change my dataSoure and reload the whole pageViewController with the new dataSource. This way I'm able to have the correct number of dots (with the dataSource and delegate functions correctly implemented). I do this with the following function :
func reloadPageViewController() {
if pageContentView.subviews.count > 1 {
for _ in 1...pageContentView.subviews.count - 1 {
pageContentView.subviews.last?.removeFromSuperview()
}
}
guard let pageViewController = storyboard?.instantiateViewController(identifier: String(describing: PageViewController.self)) as? PageViewController else {
return
}
pageViewController.removeFromParent()
self.configurePageViewController()
}
Set the dataSource property again to a new instance of a data source object that has the new number of objects.

Resources