I'm implementing a custom interactive collection view layout transition, and would like to configure it so that on calling finishInteractiveTransition with a transition layout transitionProgress of 1.0, the completion block of startInteractiveTransitionToCollectionViewLayout:completion: is fired immediately.
I require this behaviour as I would like to be able to immediately start another transition after this one has finished. With this completion block not firing immediately, I end up with nested push animation can result in corrupted navigation bar in the log, since the transition context hasn't had its completeTransition: method called yet.
As it is, even when there is no animation required, there is a small delay of about 0.05s. Is it possible to force UICollectionView to not animate this completion?
Some code...
I have a transition controller that handles both animated & interactive transitions for a navigation transition. The relevant parts of that controller are as follows:
- (void)startInteractiveTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
self.context = transitionContext;
UIView *inView = [self.context containerView];
UICollectionViewController *fromCVC = (UICollectionViewController *)[self.context viewControllerForKey:UITransitionContextFromViewControllerKey];
UICollectionViewController *toCVC = (UICollectionViewController *)[self.context viewControllerForKey:UITransitionContextToViewControllerKey];
self.transitionLayout = (MyTransitionLayout *)[fromCVC.collectionView startInteractiveTransitionToCollectionViewLayout:toCVC.collectionViewLayout completion:^(BOOL completed, BOOL finish) {
[self.context completeTransition:completed];
[inView addSubview:toCVC.view];
}];
}
- (void)updateInteractiveTransition:(CGFloat)progress
{
if (!self.context) return;
self.percentComplete = progress;
if (self.percentComplete != self.transitionLayout.transitionProgress) {
self.transitionLayout.transitionProgress = self.percentComplete;
[self.transitionLayout invalidateLayout];
[self.context updateInteractiveTransition:self.percentComplete];
}
}
- (void)finishInteractiveTransition
{
if (!self.context) return;
UICollectionViewController *fromCVC = (UICollectionViewController *)[self.context viewControllerForKey:UITransitionContextFromViewControllerKey];
[fromCVC.collectionView finishInteractiveTransition];
[self.context finishInteractiveTransition];
}
- (void)cancelInteractiveTransition
{
if (!self.context) return;
UICollectionViewController *fromCVC = (UICollectionViewController *)[self.context viewControllerForKey:UITransitionContextFromViewControllerKey];
[fromCVC.collectionView cancelInteractiveTransition];
[self.context cancelInteractiveTransition];
}
I've verified that on calling finishInteractiveTransition the transition layout's transitionProgress is exactly 1.0. According to the UIViewControllerTransitioning.h header file, the completionSpeed defaults to 1.0, resulting in a completion duration of (1 - percentComplete)*duration, so the duration should be 0, but it's not... it's taking at least a couple of run loops before the completion block is called.
Is it possible to do what I want, or will I have to implement my own version of startInteractiveTransitionToCollectionViewLayout:completion:? (not the end of the world, but I'd rather stick to the standard APIs where possible...)
Related
In my project there's a ViewController which contains a few subviews(e.g. buttons).
It shows/hides those buttons, always with animation.
It has an interface like this:
#interface MyViewController: UIViewController
- (void)setMyButtonsVisible:(BOOL)visible;
#end
And an implementation looks like this:
- (void)setMyButtonsVisible:(BOOL)visible
{
if( visible )
{
// "show"
_btn1.hidden = NO;
_btn2.hidden = NO;
[UIView animateWithDuration:0.2 animations:^{
_btn1.alpha = 1.0;
_btn2.alpha = 1.0;
}];
}
else
{
// "hide"
[UIView animateWithDuration:0.2 animations:^{
_btn1.alpha = 0.0;
_btn2.alpha = 0.0;
} completion:^(BOOL finished) {
_btn1.hidden = YES;
_btn2.hidden = YES;
}];
}
}
When [_myVC setMyButtonsVisible:NO] is called, and then after some time ( > 0.2s) [_myVC setMyButtonsVisible:YES] is called, everything is OK.
However, it setMyButtonsVisible:YES is called immediately after ( < 0.2s) setMyButtonsVisible:NO, the animations overlap and setMyButtonsVisible:NO callback is called the last.
I've tried to change "hide" duration to 0.1, it doesn't help - after "hide(0.1)"+"show(0.2)" calls, "hide" callback is called after the "show" callback and my buttons are not visible.
I've added a quick-fix by caching the visible param and checking in "hide" completion handler if the state should be !visible.
My questions are:
Why the first animation completion handler is called the last if animations overlap?
What are better approahes to discard a previous "overlapping" animation?
Check the finished flag on completion:
if (finished) {
_btn1.hidden = YES;
_btn2.hidden = YES;
}
Setting:
Assume I have 2 TableViewControllers(All in their own NavigationControllers), which contain TypeA&B items correspondingly.
In any TableView, If I tap "+" button, it will segue to a Add[?]ItemViewController("?" is The Type of Item: A or B).So normally, even if I already in the AddView, I can also switch to another View By tapping Tab Bar Icon, right?
SO How can I inhibit user to switch if they already entered one AddView?
Use the Swift code? or just change the storyboard structure?
Here is the Structure of Main.storyboard:
We've done exactly the same in our application. To hide the default
TabBar, simply override the hidesBottomBarWhenPushed method in your
parent view controller (or in every view controller in your App)
#pragma mark - Overriden UIViewController methods
- (BOOL)hidesBottomBarWhenPushed {
return YES;
}
another Solution
You can also Hide Tab bar
// pass a param to describe the state change, an animated flag and a completion block matching UIView animations completion
- (void)setTabBarVisible:(BOOL)visible animated:(BOOL)animated completion:(void (^)(BOOL))completion {
// bail if the current state matches the desired state
if ([self tabBarIsVisible] == visible) return;
// get a frame calculation ready
CGRect frame = self.tabBarController.tabBar.frame;
CGFloat height = frame.size.height;
CGFloat offsetY = (visible)? -height : height;
// zero duration means no animation
CGFloat duration = (animated)? 0.3 : 0.0;
[UIView animateWithDuration:duration animations:^{
self.tabBarController.tabBar.frame = CGRectOffset(frame, 0, offsetY);
} completion:completion];
}
// know the current state
- (BOOL)tabBarIsVisible {
return self.tabBarController.tabBar.frame.origin.y < CGRectGetMaxY(self.view.frame);
}
// illustration of a call to toggle current state
- (IBAction)pressedButton:(id)sender {
[self setTabBarVisible:![self tabBarIsVisible] animated:YES completion:^(BOOL finished) {
NSLog(#"finished");
}];
}
another Solution
You can set the UIViewController.hidesBottomBarWhenPushed instead:
DetailViewController *detailViewController = [[DetailViewController alloc] init];
detailViewController.hidesBottomBarWhenPushed = YES;
[[self navigationController] pushViewController:detailViewController animated:YES];
I have a segue being called by 5 different methods when a UIView animateWithDuration is complete. I find that if I just call the segue once (animating just one UIImageView) everything works fine, but by calling multiple this error appears:
Warning: Attempt to present <GameOver: 0x7ffc7b714280> on <Playing_Page: 0x7ffc7b7128b0> whose view is not in the window hierarchy!
The completion block (Same for all animations)
//In completion block
if (a!=b) {
[self squareOneColour];
[self squareOneMover];
}
if (a==b) {
if (self.squareOne.hidden==NO) {
[self performSegueWithIdentifier:#"gameOver" sender:self];
}
}
//Conditions must be included in answer. The are unique to each animation
Therefore when all five animations are complete (and meet conditions) it calls the segue 5 times and creates the error (I'm pretty sure, cause I did a lot of testing)
What I want is for Playing_Page to transition to GameOver without errors when the animations (and meet conditions) are finished. Any help?
You can increment an integer property in the completion block of each animation, and inspect that value in the overridden setter for that property. In the following example, that property is called counter, and I had three animations that were triggered from buttons. I'm just showing the code for one button, but the code in the completion blocks is identical.
-(void)setCounter:(NSInteger)counter {
_counter = counter;
if (_counter == 3) {
NSLog(#"All three animations are done");
// do your segue here
}
}
- (IBAction)leftButton:(id)sender {
self.leftCon.constant = 300;
[UIView animateWithDuration:5 animations:^{
[self.view layoutIfNeeded];
} completion:^(BOOL finished) {
self.counter +=1;
}];
}
I'm using an interactive custom push transition with a UIPercentDrivenInteractiveTransition. The gesture recognizer successfully calls the interaction controller's updateInteractiveTransition. Likewise, the animation successfully completes when I call the interaction controller's finishInteractiveTransition.
But, sometimes I get a extra bit of distracting animation at the end (where it seems to repeat the latter part of the animation). With reasonably simple animations, I rarely see this symptom on the iPhone 5 (though I routinely see it on the simulator when working on slow laptop). If I make the animation more computationally expensive (e.g. lots of shadows, multiple views animating different directions, etc.), the frequency of this problem on the device increases.
Has anyone else seen this problem and figured out a solution other than streamlining the animations (which I admittedly should do anyway) and/or writing my own interaction controllers? The UIPercentDrivenInteractiveTransition approach has a certain elegance to it, but I'm uneasy with the fact that it misbehaves non-deterministically. Have others seen this behavior? Does anyone know of other solutions?
To illustrate the effect, see the image below. Notice how the second scene, the red view, when the animation finishes, seems to repeat the latter part of its animation a second time.
This animation is generated by:
repeatedly calling updateInteractiveTransition, progressing update from 0% to 40%;
momentarily pausing (so you can differentiate between the interactive transition and the completion animation resulting from finishInteractiveTransition);
then calling finishInteractiveTransition to complete the animation; and
the animation controller's animation's completion block calls completeTransition for the transitionContext, in order to clean everything up.
Doing some diagnostics, it appears that it is this last step that triggers that extraneous bit of animation. The animation controller's completion block is called when the animation is finished, but as soon as I call completeTransition, it sometimes repeats the last bit of the animation (notably when using complex animations).
I don't think it's relevant, but this is my code for configuring the navigation controller to perform interactive transitions:
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.delegate = self;
self.interationController = [[UIPercentDrivenInteractiveTransition alloc] init];
}
- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
animationControllerForOperation:(UINavigationControllerOperation)operation
fromViewController:(UIViewController*)fromVC
toViewController:(UIViewController*)toVC
{
if (operation == UINavigationControllerOperationPush)
return [[PushAnimator alloc] init];
return nil;
}
- (id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController*)navigationController
interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>)animationController
{
return self.interationController;
}
My PushAnimator is:
#implementation PushAnimator
- (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning>)transitionContext
{
return 5.0;
}
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
UIViewController* toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
UIViewController* fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
[[transitionContext containerView] addSubview:toViewController.view];
toViewController.view.frame = CGRectOffset(fromViewController.view.frame, fromViewController.view.frame.size.width, 0);;
[UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
toViewController.view.frame = fromViewController.view.frame;
} completion:^(BOOL finished) {
[transitionContext completeTransition:![transitionContext transitionWasCancelled]];
}];
}
#end
Note, when I put logging statement where I call completeTransition, I can see that this extraneous bit of animation happens after I call completeTransition (even though the animation was really done at that point). This would suggest that that extra animation may have been a result of the call to completeTransition.
FYI, I've done this experiment with a gesture recognizer:
- (void)handlePan:(UIScreenEdgePanGestureRecognizer *)gesture
{
CGFloat width = gesture.view.frame.size.width;
if (gesture.state == UIGestureRecognizerStateBegan) {
[self performSegueWithIdentifier:#"pushToSecond" sender:self];
} else if (gesture.state == UIGestureRecognizerStateChanged) {
CGPoint translation = [gesture translationInView:gesture.view];
[self.interactionController updateInteractiveTransition:ABS(translation.x / width)];
} else if (gesture.state == UIGestureRecognizerStateEnded ||
gesture.state == UIGestureRecognizerStateCancelled)
{
CGPoint translation = [gesture translationInView:gesture.view];
CGPoint velocity = [gesture velocityInView:gesture.view];
CGFloat percent = ABS(translation.x + velocity.x * 0.25 / width);
if (percent < 0.5 || gesture.state == UIGestureRecognizerStateCancelled) {
[self.interactionController cancelInteractiveTransition];
} else {
[self.interactionController finishInteractiveTransition];
}
}
}
I also did it by calling the updateInteractiveTransition and finishInteractiveTransition manually (eliminating the gesture recognizer from the equation), and it still exhibits this strange behavior:
[self performSegueWithIdentifier:#"pushToSecond" sender:self];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.interactionController updateInteractiveTransition:0.40];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.interactionController finishInteractiveTransition];
});
});
Bottom line, I've concluded that this is a problem isolated to UIPercentDrivenInteractiveTransition with complex animations. I can minimize the problem by simplifying them (e.g. snapshotting and animated snapshotted views). I also suspect I could solve this by not using UIPercentDrivenInteractiveTransition and writing my own interaction controller, which would do the animation itself, without trying to interpolate the animationWithDuration block.
But I was wondering if anyone has figured out any other tricks to using UIPercentDrivenInteractiveTransition with complex animations.
This problem arises only in simulator.
SOLUTION: self.interactiveAnimator.completionSpeed = 0.999;
bug reported here: http://openradar.appspot.com/14675246
I've seen something similar. I have two possible workarounds. One is to use delayed performance in the animation completion handler:
} completion:^(BOOL finished) {
double delayInSeconds = 0.1;
dispatch_time_t popTime =
dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
BOOL cancelled = [transitionContext transitionWasCancelled];
[transitionContext completeTransition:!cancelled];
});
self.interacting = NO;
}];
The other possibility is: don't use percent-drive animation! I've never had a problem like this when driving the interactive custom animation myself manually.
The reason for this error in my case was setting the frame of the view being animated multiple times. I'm only setting the view frame ONCE and it fixed my issues.
So in this case, the frame of "toViewController.view" was set TWICE, thus making the animation have an unwanted behavior
I am recreating the UINavigationController Push animation using the new iOS 7 custom transitioning APIs.
I got the view pushing and popping fine using animationControllerForOperation
I added a edge gesture recogniser for the interactive pop gesture.
I used a UIPercentDrivenInteractiveTransition subclass and integrated code from WWDC 2013 218 - Custom Transitions Using View Controllers
It looks like it removes the fromViewController by mistake, but I don't know why.
The steps are:
Interactive pop starts
Finger is lifted after a short distance - red screenshot
The view animates back a short distance.
Red view is removed (I think) - black screenshot.
The full code is on GitHub, but here are 2 parts which I guess are important.
Gesture delegate
- (void)didSwipeBack:(UIScreenEdgePanGestureRecognizer *)edgePanGestureRecognizer {
if (state == UIGestureRecognizerStateBegan) {
self.isInteractive = YES;
[self.parentNavigationController popViewControllerAnimated:YES];
}
if (!self.isInteractive) return;
switch (state)
{
case UIGestureRecognizerStateChanged: {
// Calculate percentage ...
[self updateInteractiveTransition:percentagePanned];
break;
}
case UIGestureRecognizerStateCancelled:
case UIGestureRecognizerStateEnded: {
if (state != UIGestureRecognizerStateCancelled &&
isPannedMoreThanHalfWay) {
[self finishInteractiveTransition];
} else {
[self cancelInteractiveTransition];
}
self.isInteractive = NO;
break;
}
}
}
UIViewControllerAnimatedTransitioning protocol
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
// Grab views ...
[[transitionContext containerView] addSubview:toViewController.view];
// Calculate initial and final frames
toViewController.view.frame = initalToViewControllerFrame;
fromViewController.view.frame = initialFromViewControllerFrame;
[UIView animateWithDuration:RSTransitionVendorAnimationDuration delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
toViewController.view.frame = finalToViewControllerFrame;
fromViewController.view.frame = finalFromViewControllerFrame;
} completion:^(BOOL finished) {
[transitionContext completeTransition:YES];
}];
}
Anyone know why the screen is blank? Or Can anyone point me to some sample code. Apple don't appear have any sample code for interactive transitions using the percent driven interactions.
The first issue was a bug in the Apple sample code that I copied. The completeTransition method should have a more intelligent BOOL parameter like this:
[UIView animateWithDuration:RSTransitionVendorAnimationDuration delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
toViewController.view.frame = finalToViewControllerFrame;
fromViewController.view.frame = finalFromViewControllerFrame;
} completion:^(BOOL finished) {
[transitionContext completeTransition:![transitionContext transitionWasCancelled]];
}];
Thanks to #rounak for pointing me to the objc.io post.
This then presented another issue relating to the animation. The animation would stop, present a blank view and them carry on. This was almost defiantly a UIKit bug. The fix was to set the completionSpeed to 0.99 instead of 1.0. The default value is 1.0 so I guess that setting it to this doesn't do some side effect in their custom setter.
// self is a UIPercentDrivenInteractiveTransition
self.completionSpeed = 0.99;
I don't think you need a UIPercentDrivenInteractiveTransition subclass. I just create a new UIPercentDrivenInteractiveTransition object, hold a strong reference to it and return it in interactionControllerForAnimationController method.
This link for interactive transitions is quite helpful.