As an exercise I would like to not use a navigation controller.
I have the following project:
The 2 push segues are triggered by each button in the center of the ViewControllers. They use the following custom class:
class CustomSegue: UIStoryboardSegue {
override func perform() {
weak var firstView = self.source.view as UIView?
weak var secondView = self.destination.view as UIView?
let screenSize = UIScreen.main.bounds.size
secondView?.frame = CGRect(x: screenSize.width, y: 0.0, width: screenSize.width, height: screenSize.height)
UIApplication.shared.keyWindow?.insertSubview(secondView!, aboveSubview: firstView!)
UIView.animate(withDuration: 0.3, animations: { () -> Void in
firstView!.frame = firstView!.frame.offsetBy(dx: -1 * screenSize.width, dy: 0.0)
secondView!.frame = secondView!.frame.offsetBy(dx: -1 * screenSize.width, dy: 0.0)
}) { (_) -> Void in
self.source.present(self.destination, animated: false, completion: nil)
}
}
}
This goes extremely wrong because it creates a new ViewController object at each segue performed. The memory usage keeps going up and never down as UIApplication.shared.keyWindow.subviews is getting filled with UIViews...
The project I am working on has several ViewControllers which can call any other randomly. For this reason I didn't succeed to use UIViewController.dismiss(animated:completion:) because it systematically makes it go back to the previous ViewController.
How can I definitely remove the previous ViewController after having performed a segue?
Based on the comments, you don't want traditional "Navigation Controller" features - mainly, you don't need a "Back" button.
So, one option would be to use Child View Controllers.
Your "main" view controller would have nothing but a "container" view. On startup, you load your first VC as a Child VC, and add its view as a subview of the container. When you want to "navigate" to any other VC, load that VC as a Child VC, replace the current view in the container with the new ChildVC's view, and unload the current Child VC.
Related
I have a storyboard segue, and while showing the new view, I want an UIView to always stay on top, so the segue does not affect it. Tried animating insertSubview, but it does not have the push from bottom animation.
Here is some code I quickly whipped up showing two view controllers, the one you are going to and one from. I put the animation in a function called buttonPressed, but it should go whatever function that calls the transition. Rest of the code is pretty self explanatory.
For this to work both view controllers will need a view with same name (or different names but keep track of which is which), I use IBOutlet staticView. And then in interface builder make sure they have the same constraints or frame so that when you set on vc's static view to another it sticks to same spot.
class ViewControllerFrom: UIViewController {
#IBOutlet weak var staticView: UIView!
#IBAction func buttonPressed(_ sender: Any) {
let toVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "toVC") as! ViewControllerTo
//Add nextVC's view to ours as subview
self.view.addSubview(toVC.view)
//Set its starting height to be below current view.
toVC.view.frame = CGRect(x: 0, y: view.frame.height, width: view.frame.width, height: view.frame.height)
//This is important to make sure staticView stays in front of view animating in
view.bringSubview(toFront: staticView)
if toVC.staticView != nil {
toVC.staticView.isHidden = true
}
//I use animation duration 0.4, close to default animations by iOS.
UIView.animate(withDuration: 0.4, animations: {
toVC.view.frame.origin.y = 0
}, completion: { (success) in
if success {
//Now that view is in place, set static view from old vc to new vc and reshow it. Then do the actual presentation unanimated.
toVC.staticView.isHidden = false
toVC.staticView = self.staticView
self.present(toVC, animated: false, completion: nil)
}
})
}
}
class ViewControllerTo : UIViewController {
#IBOutlet weak var staticView: UIView!
}
I'm using a custom segue in order to transition between two view controllers. This is the segue I'm using for one of those transitions:
class SegueFromRight: UIStoryboardSegue{
override func perform() {
// Assign the source and destination views to local variables.
let src = self.source.view as UIView!
let dst = self.destination.view as UIView!
// Get the screen width and height.
let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
// Specify the initial position of the destination view.
dst?.frame = CGRect(0.0, screenHeight, screenWidth, screenHeight)
// Access the app's key window and insert the destination view above the current (source) one.
let window = UIApplication.shared.keyWindow
window?.insertSubview(dst!, aboveSubview: src!)
// Animate the transition.
UIView.animate(withDuration: 0.4, animations: { () -> Void in
src?.frame = (src?.frame.offsetBy(dx: -screenWidth, dy: 0.0))!
dst?.frame = (dst?.frame.offsetBy(dx: -screenWidth, dy: 0.0))!
}) { (Finished) -> Void in
self.source.present(self.destination as UIViewController,
animated: false,
completion: nil)
}
}
}
The segue works perfectly, however the animation is not how I'd like it. When it "pushes" the destination view controller, it's shown black. It only turns to the actual view controller as soon as the animation is finished. I guess that's because the new view controller is only loaded once the animation is finished. But how would I go about preloading the new view controller, so that the animation looks smooth?
The unwinding segue does not display that black animation, as the destination view controller (the previous source view controller) is already loaded of course.
This is likely your problem dst?.frame = CGRect(0.0, screenHeight, screenWidth, screenHeight).
Try this instead dst?.frame = CGRect(screenWidth, 0.0, screenWidth, screenHeight).
Your original line sets the destination view to be off the bottom of the screen rather than off to the right edge of the screen. When you animate the views by the screen width the destination slides from directly below the screen to below and to the left.
In my UIStoryboardSegue subclass, I use presentViewController at the end of the perform method, this cause viewDidAppear/viewWillAppear to be called twice?
How can I prevent this?
Thanks
Current code:
override func perform() {
// Assign the source and destination views to local variables
let sourceView = sourceViewController.view as UIView!
let destView = destinationViewController.view as UIView!
// Get the screen width and height
let screenWidth = UIScreen.mainScreen().bounds.size.width
let screenHeight = UIScreen.mainScreen().bounds.size.height
// Specify the initial position of the destination view
destView.frame = CGRectMake(0.0, screenHeight, screenWidth, screenHeight)
// Add the destination view to the window
let window = UIApplication.sharedApplication().keyWindow
window?.insertSubview(destView, aboveSubview: sourceView)
// Animate the transition
UIView.animateWithDuration(0.7, animations: { () -> Void in
// Scale down the source view
sourceView.transform = CGAffineTransformScale(sourceView.transform, 0.90, 0.90)
}) { (Finished) -> Void in
}
UIView.animateWithDuration(1.0, delay: 0.2, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.7, options: .CurveEaseOut, animations: { () -> Void in
destView.frame = CGRectOffset(destView.frame, 0.0, -screenHeight)
}) { (finished) -> Void in
self.sourceViewController.presentViewController(self.destinationViewController as UIViewController, animated: false, completion: nil)
}
}
I see now that without presentViewController the new controller is destroyed soon after the animation custom segue. I see why we need it.
The reason why viewDidAppear gets called twice is that you first insert the viewcontroller as a subview into the keyWindow. (which triggers the viewDidAppear)
and then present the viewcontroller. (which triggers the viewDidAppear also)
This brings also some side effects to your app because you will end up with a viewHierachy like:
-- KeyWindow
---- FirstVC View
---- SecondVC View
---- UITransitionView (because of the presentVC)
------- SecondVC View
If you want to achieve this swipe/scroll transition why not just use a scrollView and have childviewcontrollers in it?
The other solution for this would be to use a custom transition and simply call presentViewController with a custom transition as described here: http://www.raywenderlich.com/113845/ios-animation-tutorial-custom-view-controller-presentation-transitions
Attempting to write a custom segue where the source view is scaled out, while changing the alpha of the destination to fade the destination in. The destination is a MKMapView, so I want it updating as the fade occurs.
With what I've tried I end up with the source and designation scaling out simultaneously, and I can't get just the source view to scale out.
class Map_Segue: UIStoryboardSegue {
override func perform()
{
var sourceViewController : UIViewController = self.sourceViewController as UIViewController
var destinationViewController : UIViewController = self.destinationViewController as UIViewController
destinationViewController.view.alpha = 0 sourceViewController.addChildViewController(destinationViewController) sourceViewController.view.addSubview(destinationViewController.view)
UIView.animateWithDuration(2.0,delay:1.0,options: UIViewAnimationOptions.CurveEaseInOut, // delay of 1 second for aesthetics
animations:
{
sourceViewController.view.transform = CGAffineTransformScale(sourceViewController.view.transform, 100.0, 100.0);
destinationViewController.view.alpha = 1;
},
completion:
{ (finished:Bool)->Void in
destinationViewController.didMoveToParentViewController(sourceViewController);
}
)
}
}
I've tried autoresizesSubviews=false, but that doesn't seem to do anything.
I've tried setting the destination transform in the animation to be 1/100 (and set the options to UIViewAnimationOptions.CurveLinear which has the final result correct, but the transition effect is wrong (map in the background scaled up then down again)
I'm sure this should be easy, and I'm missing a trick as I'm new to this.
Anyone got any ideas?
Update:
I've found that (somewhat obviously) I should use sourceViewController.view.superview?.insertSubview( destinationViewController.view, atIndex:0) to insert it alongside the original source view, rather than as a child of it, that way, obviously, the transform is independent, not with respect to the views parent (which it will be as a subview). The problem then is swapping to the new view. Using the method I had, viewWillAppear and similar are not called, and the changing over the views does not work. If I call presentViewController, then we get a glitch when viewWillAppear is called.
Solution so far
Forget using custom segues. Followed the suggestion and placed a UIImageView on top of the map view, and had a beautiful animating fade in about 5 minutes of coding.
I think you are a bit confused with parent and child view controllers etc. It is sufficient to temporarily add the second view controller's view to the first one, perform the transitions and then clean up.
I tested the following in a simple sample project. Note that I am adding the second view controller's view to the window rather than the first view controller's view because otherwise it would also get scaled up.
override func perform() {
let first = self.sourceViewController as ViewController
let second = self.destinationViewController as ViewController
second.view.alpha = 0
first.view.window!.addSubview(second.view)
UIView.animateWithDuration(2.0, delay: 0.0,
options: .CurveEaseInOut, animations: { () -> Void in
first.view.transform = CGAffineTransformMakeScale(100.0, 100.0)
second.view.alpha = 1.0
})
{ (finished: Bool) -> Void in
second.view.removeFromSuperview()
first.presentViewController(second, animated: false, completion: nil)
}
}
I have sideViewController with a button and Action, which present new view controller by clicking this button.
class sideViewController: UIViewController {
#IBOutlet var buttonVC1 : UIButton!
#IBAction func goToVC1 () {
var VC1 = self.storyboard.instantiateViewControllerWithIdentifier("ViewController") as ViewController
presentViewController(VC1, animated:true, completion: nil)
}
}
I use this in main view controller:
class ViewController: UIViewController {
var menu : sideViewController!
override func viewDidLoad() {
super.viewDidLoad()
menu = self.storyboard.instantiateViewControllerWithIdentifier("menu") as sideViewController
menu.view.frame = CGRect(x: 0, y: 0, width: 160, height: 480)
view.addSubview(menu.view)
}
when I click this button, the problem is: "Presenting view controllers on detached view controllers is discouraged"
What should I do to fix this?
I just ran into this same warning myself, and realized that I'm getting it because when I was calling
self.presentViewController
I was calling it on a view controller that wasn't attached to the UIWindow through the view hierarchy. You need to change what your doing to delay calling presentViewController until you know the view is on the view stack. This would be done in ViewDidLoad or ViewDidAppear, or if your coming from a background state, waiting until your app is in the active state
Use this to make sure you are on the main thread
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.presentViewController(VC1, animated: true, completion: nil)
})
Problem
iOS is complaining that some other view(the detached view) which came after the main view is presenting something. It can present it, which it does apparently, but it's discouraged as it's not a good practice to do so.
Solution
Delegate/protocol pattern is suitable to solve this issue. By using this pattern, the action will be triggered inside the SideVC although this trigger will be sent to the MainVC and be performed there.
Therefore, since the action will be triggered by the MainVC, from iOS's perspective, it will all be safe and sound.
Code
SideVC:
protocol SideVCDelegate: class {
func sideVCGoToVC1()
}
class sideVC: UIViewController {
weak var delegate: SideVCDelegate?
#IBOutlet var buttonVC1: UIButton!
#IBAction func goToVC1 () {
delegate.sideVCGoToVC1()
}
MainVC
class MainVC: UIViewController, SideVCDelegate {
var menu: sideVC!
override func viewDidLoad() {
super.viewDidLoad()
menu = self.storyboard?.instantiateViewControllerWithIdentifier("menu") as sideViewController
menu.delegate = self
menu.view.frame = CGRect(x: 0, y: 0, width: 160, height: 480)
view.addSubview(menu.view)
}
// MARK: - SideViewControllerDelegate
func sideViewControllerGoToVC1() {
menu.view.removeFromSuperview()
var VC1 = self.storyboard?.instantiateViewControllerWithIdentifier("ViewController") as ViewController
presentViewController(VC1, animated:true, completion: nil)
}
}
Note
Apart from the question you've asked, the below lines seems somewhat vague.
var VC1 = self.storyboard?.instantiateViewControllerWithIdentifier("ViewController") as ViewController
menu.view.frame = CGRect(x: 0, y: 0, width: 160, height: 480)
You're obtaining a view controller from your storyboard which has a frame when you designed it inside Interface Builder but you're changing it afterwards. It's not a good practice to play with the frames of views once they're created.
Maybe you've intended to do something else but most likely, it's a problematic piece of code.
Swift 5
In the UIKit view hierarchy, view controllers can either be "attached" or "detached", which I put in quotes because they're never explained in documentation. From what I've observed, attached view controllers are simply view controllers that are directly chained to the key window.
Therefore, the nearest attached view controller would obviously be the root view controller itself, since it's directly owned by the key window. This is why presenting from the root view controller remedies warnings about presenting on detached view controllers.
To present a subsequent view controller (a second one), you must find the next nearest and available attached view controller (I say available because the root view controller is currently occupied presenting the current view controller; it cannot present any more view controllers). If the root is presenting a plain view controller (meaning, not a container view controller like a navigation controller), then the next nearest attached view controller is that view controller. You can present from self without any warnings, since it's directly chained to the root, which is directly chained to the key window. However, if the root presented a container view controller, like a navigation controller, then you could not present from any of its children, because they are not directly chained to the root—the parent/container is. Therefore, you would have to present from the parent/container.
To make this easier, you can subclass UIViewController and add a convenience method for finding the nearest available attached view controller.
class XViewController: UIViewController {
var rootViewController: UIViewController? {
return UIApplication.shared.keyWindow?.rootViewController
}
/* Returns the nearest available attached view controller
(for objects that seek to present view controllers). */
var nearestAvailablePresenter: UIViewController? {
guard let root = rootViewController else {
return nil
}
if root.presentedViewController == nil {
return root // the root is not presenting anything, use the root
} else if let parent = parent {
return parent // the root is currently presenting, find nearest parent
} else {
return self // no parent found, present from self
}
}
}
Usage
class SomeViewController: XViewController {
let modal = AnotherViewController()
nearestAvailablePresenter?.present(modal, animated: true, completion: nil)
}
Here this might help you. I got my error fixed with this
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(0.001 * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue(), { () -> Void in
self.performSegueWithIdentifier("SegueName", sender: self)
})
Good luck..