I am trying to move a UIView programmatically using the following method:
-(void)animatePlaybackLine: (int) currentBeat{
CGRect newFrame = CGRectMake(currentBeat*eighthNoteWidth, 0, eighthNoteWidth, 320);
[playbackLine setFrame:newFrame];
NSLog(#"Line animated to %i", currentBeat);
NSLog(#"New frame origin %f", playbackLine.frame.origin.x);
}
When the method is called, the NSLogs show that the variable currentBeat is incrementing as it should, and the frame of playbackLine (my UIView) appears to be moving as it should. However, the object on the screen doesn't move. I have also tried setting the bounds and the center instead of the frame, and all of them have similar results. I also tried using an animation instead of setting the frame, to no avail.
Is there something else I should be doing to make the image onscreen show the changing frame?
I'm guessing you're calling that method in a loop? iOS isn't going to redraw the screen until your code finishes executing. You can't loop like this and see iterative results.
To animate views, you should use the native support UIKit gives you. In particular, check out the Animations section in the UIView class reference.
Try this
[UIView animateWithDuration:0.3
delay:0.0
options: UIViewAnimationCurveEaseOut
animations:^{
datePickerView.frame = imageFrame;
}
completion:^(BOOL finished){
self.datePickerViewFlag = NO;
}];
Related
I have a UIView subclass that draws a circle whose radius changes (with nice bouncy animations). The view is deciding the size of the circle.
I want this UIView subclass to change its frame size to match the animated changes to the circle radius, and I want these changes to modify any NSLayoutConstraints connected to the view (so that views that are constrained to the edge of the circle will move as the circle resizes).
I understand that implementing -(CGSize)intrinsicContentSize and calling invalidateIntrinsicContentSize when the radius changes will tell constraints to update, but I cant figure out how to animate the changes to intrinsicContentSize.
Calling invalidateIntrinsicContentSize from within a [UIView animateWith... block just instantly updates the layout.
Is this even possible, and is there a workaround/better approach?
invalidateIntrinsicContentSize works well with animations and layoutIfNeeded. The only thing you need to consider is, that changing the intrinsic content size invalidates the layout of the superview. So this should work:
[UIView animateWithDuration:0.2 animations:^{
[self invalidateIntrinsicContentSize];
[self.superview setNeedsLayout];
[self.superview layoutIfNeeded];
}];
Swift version of #stigi's answer which worked for me:
UIView.animate(withDuration: 0.2, animations: {
self.invalidateIntrinsicContentSize()
self.superview?.setNeedsLayout()
self.superview?.layoutIfNeeded()
})
Width / height constraint doesn't help? Keep reference of this constraint and ...
[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1
constant:myViewInitialWidth];
... when you do want to animate myView resize, do this ...
self.viewWidthConstraint.constant = 100; // new width
[UIView animateWithDuration:0.3 animations:^{ [view layoutIfNeeded]; }];
... do the same thing for the height.
Depends on your other constraints, maybe you will be forced to raise priority of these two constraints.
Or you can subclass UIView, add - (void)invalidateIntrinsicContentSize:(BOOL)animated and fake it by yourself. Get new size from - (CGSize)intrinsicContentSize and animate it by animating width / height constraints. Or add property to enable / disable animations and override invalidateIntrinsicContentSize and do it inside this method. Many ways ...
In the code below, intrinsic class is the class that has just changed it's size on changing a variable. To animate the intrinsic class only use the code below. If it impacts other objects higher up the view hierarchy then replace self.intrinsic class with the top level view for setNeedsLayout and layoutIfNeeded.
[UIView animateWithDuration:.2 animations:^{
self.intrinsicClass.numberOfWeeks=8;
[self.intrinsicClass setNeedsLayout];
[self.intrinsicClass layoutIfNeeded];
}];
None of this has worked for me. I have a UILabel which I am setting with a NSAttributedString. The text is multiline and wrapping on word boundaries. Therefore the height is variable. I've tried this:
[UIView animateWithDuration:1.0f animations:^{
self.label = newLabelText;
[self.label invalidateIntrinsicContentSize];
[self.view setNeedsLayout];
[self.view layoutIfNeeded];
}];
And a number of variations. None work. The label immediately changes it's size and then slides into it's new position. So the animation of the labels position ons screen is working. But the animating of the label's size change is not.
Well for Swift 4/3 this works and I think this is best practise. If you have a UIView with a UILabel in it and the UIView adapts the frame from the UILabel, use this:
self.theUILabel.text = "text update"
UIView.animate(withDuration: 5.0, animations: {
self.theUIView.layoutIfNeeded()
})
The normal self.view.layoutIfNeeded() will work most of the time as well.
I have two IBOutlet variables connected to two instances of UIView in Interface Builder, called blankView and fadedBGView in my ViewController.
How can I set up this code so that the blankView instance will fade into fadedBGView, using the UIViewAnimationOptionTransitionCrossDissolve transition, and the two UIViews can simultaneously transform (move) from their current position (they have equal positions) to 0,0?
What's happening is the fade occurs, and then the fadedBGView view abruptly moves to 0,0.
In other words, I'd like to have the first UIView fade into the second, while simultaneously moving up the screen.
Hopefully this is clear enough to answer.
Best...SL
[UIView transitionFromView:blankView
toView:fadedBGView
duration:1.0
options:UIViewAnimationOptionTransitionCrossDissolve
completion:^(BOOL finished) {
[blankView removeFromSuperview];
}];
[UIView commitAnimations];
CGRect frame = fadedBGView.frame;
frame.origin.x = 0;
frame.origin.y = 0;
[UIView animateWithDuration:1.0 animations:^{
NSLog(#"UIView Transition/Move Called");
fadedBGView.frame = frame;
}];
iOS 4 and newer provides block-based animations, which your code is already using:
+[UIView animateWithDuration:animations:];
+[UIView animateWithDuration:animations:completion:];
Within the animation block, you can set multiple destination values. See Apple's UIView documentation for a reference to the animatable properties. So within one block, you can modify frames, and alpha (transparency) values of views. I'm not sure how the cross dissolve animation works, but if it's simply one view going from 0 to 1, and another view going from 1 to 0, that's easy to implement.
Instead of
UIViewAnimationOptionTransitionCrossDissolve
use
UIViewAnimationOptionTransitionCrossDissolve | UIViewAnimationOptionAllowAnimatedContent
UIViewAnimationOptionAllowAnimatedContent option allows additional animations during transition. Make sure your fadedBGView has correct starting frame.
Same code as in a previous question, but a different issue.
I've created a custom animation to add a view controller to a UINavigationController. This code scales a view to 80% the original size, then flips it, then scales it back up to its original size:
[UIView animateWithDuration:scaleDuration delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
// Scale the controllers' views down.
self.view.transform = CGAffineTransformScale(self.view.transform, 0.8, 0.8);
} completion:^(BOOL finished) {
// Transition to the new view and push on the new view controller.
[UIView transitionWithView:self.view duration:1 options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionTransitionFlipFromLeft animations:^{
[self pushViewController:viewController animated:NO];
} completion:^(BOOL finished) {
[UIView animateWithDuration:scaleDuration delay:0 options:UIViewAnimationOptionCurveLinear animations:
^{
// Scale back to the original size.
self.view.transform = CGAffineTransformScale(self.view.transform, 1.25, 1.25);
} completion:nil];
}];
}];
The issue is that, when the animation completes, the new view is displayed very nicely, except that it is drawn under the task bar. That is, it draws in at screen origin 0,0, rather than 0,20. The "Status Bar" option is set in IB (to "Black"), and, naturally, this does not happen if I use a standard UINavigationController push animation, only my custom one. If I rotate the device after the animation, the redraw on rotation moves it to the proper place. But how do I get it to do that in the first place?
As an added wrinkle, it does not draw under the task bar if I move the pushViewController:animated: call a line down to the completion: block (though then the view appears to flip to itself and then suddenly show the new view, of course).
I found the only work around so far is hide the navigationbar and then show it.
after you set your transform, add following 2 lines:
[self setNavigationBarHidden:YES];
[self setNavigationBarHidden:NO];
It's ugly but works, I am also looking for a better solution.
note: layoutsubview, setNeedsLayout won't work.
I'm looking for a way to implement consecutive animations using nested animation blocks.
Somewhat complicated by happening inside a UIScrollView, the size of three UIImageViews (there are many images, and as I scroll through them I constantly swapping out the images in the UIImageViews).
When a scroll is finished, I want to switch out the image in the (visible) middle UIImageView, three times, then back to the original view. I'm trying it thus:
- (void) doAnimation {
// get the animation frames, along with the current image
NSString *swap1 = #"first.png";
NSString *swap2 = #"second.png";
UIImage *original = currentPage.image;
UIViewAnimationOptions myOptions = UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction;
[UIView animateWithDuration:2.0 delay:2.0 options:myOptions
animations:^{ [currentPage setImage:[UIImage imageNamed:swap1]]; }
completion:^(BOOL finished) {
[UIView animateWithDuration:2.0 delay:2.0 options:myOptions
animations:^{ [currentPage setImage:[UIImage imageNamed:swap2]]; }
completion:^(BOOL finished) {
[UIView animateWithDuration:2.0 delay:2.0 options:myOptions
animations:^{ [currentPage setImage:[UIImage imageNamed:swap1]]; }
completion:^(BOOL finished) {
[currentPage setImage:original]; }]; }]; }];
}
When I run this, there is no duration, no delay, it all happens at once, almost too fast for the eye to see. Could this be because "currentPage" is a UIImageView? (Similar to this question?)
There's no delay because UIImageView.image isn't an animateable property. As such, the UIView animation machinery will have no animations to set up and will just call your completion block immediately.
What sort of animation did you expect? You can attach a CATransition object to the underlying layer to get a simple cross-fade, Just use [imageView.layer addAnimation:[CATransition animation] forKey:nil] to get the crossfade with the default values (you can customize the timing by modifying properties of the CATransition before attaching it to the layer). To achieve the subsequent animations, you can either use the delegate property of CAAnimation (CATransition's superclass) to learn when it's done and fire your second one, or you could just use -performSelector:withObject:afterDelay: to start your next animation step after a user-defined delay. The delegate method is going to be more accurate with regards to timing, but the performSelector method is a bit easier to write. Sadly, CAAnimation doesn't support a completion block.
Another approach for you to transition from one image view to another is by using the block animation function transitionFromView:toView:duration:options:completion as discussed in "Creating Animated Transitions Between Views". You would do this instead of animateWithDuration to change images.
I'm trying to transform a UISearchBar, like in Mobile Safari: touch in the search field and it grows while the location field shrinks.
My current animation to alter the width and position of the search field only animates the position: just before it slides to the right place, it simply snaps out to the right width. Here's my code:
[UIView beginAnimations:#"searchGrowUp" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIView setAnimationDuration:0.5f];
[UIView setAnimationDelegate:self];
CGFloat findFieldWidth = findField.frame.size.width;
CGFloat urlFieldWidth = urlField.frame.size.width;
CGRect findFieldFrame = findField.frame;
CGRect urlFieldFrame = urlField.frame;
findFieldFrame.origin.x = findFieldFrame.origin.x - 150.0f;
findFieldFrame.size.width = findFieldWidth + 150.0f;
urlFieldFrame.size.width = urlFieldWidth - 150.0f;
urlField.frame = urlFieldFrame;
findField.frame = findFieldFrame;
[UIView commitAnimations];
I've modified this code slightly for the sake of presenting it here, but I hope this gives the gist.
Any guesses as to why this is happening would be appreciated!
Cheers,
Aaron.
I figured it out thanks to this post: Changing the size of the UISearchBar TextField?
Turns out the contents of a UISearchBar don't resize properly along with the outer layer. So you have to call -layoutSubviews: within the animation block after the frame is set on the searchbar. So the block ends like:
[findField setFrame:CGRectMake(findField.bounds.origin.y, findField.bounds.origin.y, findFieldWidth, findField.bounds.size.height)];
[findField layoutSubviews];
[UIView commitAnimations];
Props to Nick Farina!
I had the same problem when trying to animate the width of a UISearchBar.
On iOS 4 and later, I found that using UIViewAnimationOptionLayoutSubviews as an option for
+[UIView animateWithDuration:delay:options:animations:completion:]
fixed it.
The accepted answer works but according to Apple docs you "should not call this method". The clean solution is to use layoutIfNeeded method:
[UIView animateWithDuration:UINavigationControllerHideShowBarDuration
delay:0.f
options:UIViewAnimationOptionCurveEaseInOut
animations:^{
[searchBar setFrame: ...
[searchBar layoutIfNeeded];
...
Enjoy!
Sorry this is a bit old, but I was running into a similar problem.
I didn't want to use layoutSubviews because the documentation says you shouldn't call that method directly.
What I did to solve my problem was call sizeToFit on the subview within the animation block.