Is there a way to change the speed of the animation when scrolling a UITableView using setContentOffset:animated:? I want to scroll it to the top, but slowly. When I try the following, it causes the bottom few cells to disappear before the animation starts (specifically, the ones that won't be visible when the scroll is done):
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:3.0];
[self.tableView setContentOffset:CGPointMake(0, 0)];
[UIView commitAnimations];
Any other way around this problem? There is a private method _setContentOffsetAnimationDuration that works, but I don't want to be rejected from the app store.
[UIView animateWithDuration:2.0 animations:^{
scrollView.contentOffset = CGPointMake(x, y);
}];
It works.
Setting the content offset directly did not work for me. However, wrapping setContentOffset(offset, animated: false) inside an animation block did the trick.
UIView.animate(withDuration: 0.5, animations: {
self.tableView.setContentOffset(
CGPoint(x: 0, y: yOffset), animated: false)
})
I've taken nacho4d's answer and implemented the code, so I thought it would be helpful for other people coming to this question to see working code:
I added member variables to my class:
CGPoint startOffset;
CGPoint destinationOffset;
NSDate *startTime;
NSTimer *timer;
and properties:
#property (nonatomic, retain) NSDate *startTime;
#property (nonatomic, retain) NSTimer *timer;
and a timer callback:
- (void) animateScroll:(NSTimer *)timerParam
{
const NSTimeInterval duration = 0.2;
NSTimeInterval timeRunning = -[startTime timeIntervalSinceNow];
if (timeRunning >= duration)
{
[self setContentOffset:destinationOffset animated:NO];
[timer invalidate];
timer = nil;
return;
}
CGPoint offset = [self contentOffset];
offset.x = startOffset.x +
(destinationOffset.x - startOffset.x) * timeRunning / duration;
[self setContentOffset:offset animated:NO];
}
then:
- (void) doAnimatedScrollTo:(CGPoint)offset
{
self.startTime = [NSDate date];
startOffset = self.contentOffset;
destinationOffset = offset;
if (!timer)
{
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01
target:self
selector:#selector(animateScroll:)
userInfo:nil
repeats:YES];
}
}
you'd also need timer cleanup in the dealloc method. Since the timer will retain a reference to the target (self) and self has a reference to the timer, some cleanup code to cancel/destroy the timer in viewWillDisappear is likely to be a good idea too.
Any comments on the above or suggestions for improvement would be most welcome, but it is working very well with me, and solves other issues I was having with setContentOffset:animated:.
There is no a direct way of doing this, nor doing the way you wrote it. The only way I can accomplish this is by making the movement/animation by my own.
For example move 1px every 1/10 second should simulate a very slow scroll animation. (Since its a linear animation maths are very easy!)
If you want to get more realistic or fancy and simulate easy-in easy-off effect then you need some maths to calculate a bezier path so you can know the exact position at every 1/10 second, for example
At least the first approach shouldn't be that difficult.
Just use or -performSelector:withObject:afterDelay or NSTimerswith
-[UIScrollView setContentOffset:(CGPoint*)];`
Hope it helps
UIView calculates final view and then animates it. That's why cells that invisible on finish of animation invisible on start too. For prevent this needed add layoutIfNeeded in animation block:
[UIView animateWithDuration:2.0 animations:^{
[self.tableView setContentOffset:CGPointMake(0, 0)];
[self.tableView layoutIfNeeded]
}];
Swift version:
UIView.animate(withDuration: 2) {
self.tableView.contentOffset.y = 10
self.tableView.layoutIfNeeded()
}
I'm curious as to whether you found a solution to your problem. My first idea was to use an animateWithDuration:animations: call with a block setting the contentOffset:
[UIView animateWithDuration:2.0 animations:^{
scrollView.contentOffset = CGPointMake(x, y);
}];
Side effects
Although this works for simple examples, it also has very unwanted side effects. Contrary to the setContentOffset:animated: everything you do in delegate methods also gets animated, like the scrollViewDidScroll: delegate method.
I'm scrolling through a tiled scrollview with reusable tiles. This gets checked in the scrollViewDidScroll:. When they do get reused, they get a new position in the scroll view, but that gets animated, so there are tiles animating all the way through the view. Looks cool, yet utterly useless. Another unwanted side effect is that possible hit testing of the tiles and my scroll view's bounds is instantly rendered useless because the contentOffset is already at a new position as soon as the animation block executes. This makes stuff appear and disappear while they're still visible, as to where they used to be toggled just outside of the scroll view's bounds.
With setContentOffset:animated: this is all not the case. Looks like UIScrollView is not using the same technique internally.
Is there anyone with another suggestion for changing the speed/duration of the UIScrollView setContentOffset:animated: execution?
You can set the duration as follows:
scrollView.setValue(5.0, forKeyPath: "contentOffsetAnimationDuration") scrollView.setContentOffset(CGPoint(x: 100, y: 0), animated: true)
This will also allow you to get all of your regular delegate callbacks.
https://github.com/dominikhofmann/PRTween
subclass UITableview
#import "PRTween.h"
#interface JPTableView : UITableView{
PRTweenOperation *activeTweenOperation;
}
- (void) doAnimatedScrollTo:(CGPoint)destinationOffset
{
CGPoint offset = [self contentOffset];
activeTweenOperation = [PRTweenCGPointLerp lerp:self property:#"contentOffset" from:offset to:destinationOffset duration:1.5];
}
IF all your trying to do is scroll your scrollview I think you should use scroll rect to visible. I just tried out this code
[UIView animateWithDuration:.7
delay:0
options:UIViewAnimationOptionCurveEaseOut
animations:^{
CGRect scrollToFrame = CGRectMake(0, slide.frame.origin.y, slide.frame.size.width, slide.frame.size.height + kPaddingFromTop*2);
CGRect visibleFrame = CGRectMake(0, scrollView.contentOffset.y,
scrollView.frame.size.width, scrollView.frame.size.height);
if(!CGRectContainsRect(visibleFrame, slide.frame))
[self.scrollView scrollRectToVisible:scrollToFrame animated:FALSE];}];
and it scrolls the scrollview to the location i need for whatever duration i am setting it for. The key is setting animate to false. When it was set to true, the animation speed was the default value set by the method
For people who also have issues with disappearing items while scrolling a UITableView or a UICollectionView you can expand the view itself so that we hold more visible items. This solution is not recommended for situations where you need to scroll a great distance or in situations where the user can cancel the animation. In the app I'm currently working on I only needed to let the view scroll a fixed 100px.
NSInteger scrollTo = 100;
CGRect frame = self.collectionView.frame;
frame.size.height += scrollTo;
[self.collectionView setFrame:frame];
[UIView animateWithDuration:0.8 delay:0.0 options:(UIViewAnimationOptionCurveEaseIn) animations:^{
[self.collectionView setContentOffset:CGPointMake(0, scrollTo)];
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.8 delay:0.0 options:(UIViewAnimationOptionCurveEaseIn) animations:^{
[self.collectionView setContentOffset:CGPointMake(0, 0)];
} completion:^(BOOL finished) {
CGRect frame = self.collectionView.frame;
frame.size.height -= scrollTo;
[self.collectionView setFrame:frame];
}];
}];
I use transitionWithView:duration:options:animations:completion:
[UIView transitionWithView:scrollView duration:3 options:(UIViewAnimationOptionCurveLinear) animations:^{
transitionWithView:scrollView.contentOffset = CGPointMake(contentOffsetWidth, 0);
} completion:nil];
UIViewAnimationOptionCurveLinear is an option make animation to occur evenly over.
While I found that in an animation duration, the delegate method scrollViewDidScroll did not called until animation finished.
You can simply use block based animation to animate the speed of scrollview.
First calculate the offset point to which you want to scroll and then simply pass that offset value as here.....
[UIView animateWithDuration:1.2
delay:0.02
options:UIViewAnimationCurveLinear
animations:^{
[colorPaletteScrollView setContentOffset: offset ];
}
completion:^(BOOL finished)
{ NSLog(#"animate");
} ];
here colorPaletteScrollView is my custom scrollview and offset is the value passed .
this code works perfectly fine for me.
Is there a reason you're using setContentOffset and not scrollRectToVisible:animated:?
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
I would recommend doing it like this:
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:3.0];
[self.tableView scrollRectToVisible:CGRectMake(0, 0, 320, 0) animated:NO];
[UIView commitAnimations];
Unless that doesnt work. I still think you should try it.
Actually TK189's answer is partially correct.
To achieve a custom duration animated contentOffset change, with proper cell reuse by UITableView and UICollectionView components, you just have to add a layoutIfNeeded call inside the animations block:
[UIView animateWithDuration:2.0 animations:^{
tableView.contentOffset = CGPointMake(x, y);
[tableView layoutIfNeeded];
}];
On Xcode 7.1 - Swift 2.0 :
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
dispatch_async(dispatch_get_main_queue()) {
UIView.animateWithDuration(0, animations: { self.scrollView!.setContentOffset(CGPointZero,animated: true) })
}
return true
}
OR
func textFieldShouldReturn(textField: UITextField) -> Bool {
if(textField.returnKeyType == UIReturnKeyType.Next) {
password.becomeFirstResponder()
}
dispatch_async(dispatch_get_main_queue()) {
UIView.animateWithDuration(0, animations: { self.scrollView!.setContentOffset(CGPointZero,animated: true) })
}
textField.resignFirstResponder()
return true
}
Note: self.scrollView!.setContentOffset(CGPointZero,animated: true) can have different positions depending on the requirement
Example:
let scrollPoint:CGPoint = CGPointMake(0,textField.frame.origin.y/2);
scrollView!.setContentOffset(scrollPoint, animated: true);
I wanted to change the contentOffSet of tableview when textfield begins to edit.
Swift 3.0
func textFieldDidBeginEditing(_ textField: UITextField) {
DispatchQueue.main.async {
UIView.animate(withDuration: 0, animations: {
self.sampleTableView.contentOffset = CGPoint(x: 0, y: 0 - (self.sampleTableView.contentInset.top - 200 ))
})
}
}
Related
I'm scrolling through a scroll view dynamically, it works using
-(IBAction) animateTestingTwo{
[UIView animateWithDuration:4 animations:^{scroller.contentOffset = CGPointMake(0, 2000);}];
}
However the animation curve is not linear, it needs to be so I'm using this:
-(IBAction) animateTestingTwo{
[UIView animateWithDuration:4 options:UIViewAnimationOptionCurveLinear animations:^{scroller.contentOffset = CGPointMake(0, 2000);}];
}
However it isn't working. Any ideas?
Thanks!!
If the duration doesn't matter to you, this can be used:
[scrollview setContentOffset:CGPointMake(10, 200) animated:YES];
Acconding to the documentation:
animated
YES to animate the transition at a constant velocity to the new offset, NO to make the transition immediate.
You can also try to do this inside an animation block to see what happens.
I am using the EGORefreshTableHeaderView [1] to fetch new data from a server into a UITableView.
This works pretty good but in iOS 5.1 the EGORefreshTableHeaderView does not scroll back into the intended height when the user releases the pull down. Normally it should scroll back to an contentInset of 60px. Then the loading view should be visible for the time which the loading process takes and after that scroll back to 0px inset.
The first scroll-back should happen in the egoRefreshScrollViewDidEndDragging:scrollView method.
- (void)egoRefreshScrollViewDidEndDragging:(UIScrollView *)scrollView {
BOOL _loading = NO;
if ([_delegate respondsToSelector:#selector(egoRefreshTableHeaderDataSourceIsLoading:)]) {
_loading = [_delegate egoRefreshTableHeaderDataSourceIsLoading:self];
}
if (scrollView.contentOffset.y <= - 65.0f && !_loading) {
if ([_delegate respondsToSelector:#selector(egoRefreshTableHeaderDidTriggerRefresh:)]) {
[_delegate egoRefreshTableHeaderDidTriggerRefresh:self];
}
[self setState:EGOOPullRefreshLoading];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.2];
scrollView.contentInset = UIEdgeInsetsMake(60.0f, 0.0f, 0.0f, 0.0f);
[UIView commitAnimations];
//I've also tried it with block animations! But doesn't work!
/*[UIView animateWithDuration:0.2 animations:^{
scrollView.contentInset = UIEdgeInsetsMake(60.0f, 0.0f, 0.0f, 0.0f);
}];*/
}
}
The problem is that when a user releases the scroll view on the half of the screen (shown in the screenshot below), the scrollview does not bounce back into the 60px inset where it should reload the data.
My first idea was that it is because of the animations. So I changed it to block animations but nothing changes. I guess the problem is that the animations are not executed on commitAnimations rather at the end of the loading.
Does anyone have a solution for this?
[1]... https://github.com/enormego/EGOTableViewPullRefresh
I would pull up their demo application and follow their delegate methods.
put this inside didEndDragging:
[_delegate egoRefreshScrollViewDidEndDragging:scrollView];
I am having some issues with some animation stuff in an iPad application. I have four UIButtons that are on the screen when the app launches.
I basically want the app to load and the four buttons to animate into view one at a time from the top of the screen into place.
I have the following which kind of animates it but I am struggling with it.
-(void)viewWillAppear:(BOOL)animated
{
CGPoint newLeftCenter = CGPointMake( 15.0f + myCocoButton.frame.size.width / 2.0f, myCocoButton.center.y);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:4.0f];
myCocoButton.center = newLeftCenter;
[UIView commitAnimations];
}
The current code that I have does animate the button but not in the way I want. I can't get my head around how to actually place it exactly where I want it.
In your storyboard, lay out your buttons in their final positions.
In viewWillAppear:, save the location of each button and move the button off-screen:
#implementation MyViewController {
CGPoint _button0TrueCenter;
CGPoint _button1TrueCenter;
CGPoint _button2TrueCenter;
CGPoint _button3TrueCenter;
}
static void moveButtonAndSaveCenter(UIButton *button, CGPoint offscreenCenter, CGPoint *trueCenter) {
*trueCenter = button.center;
button.center = offscreenCenter;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if (animated) {
moveButtonAndSaveCenter(self.button0, CGPointMake(-100, 100), &_button0TrueCenter);
moveButtonAndSaveCenter(self.button1, CGPointMake(420, 100), &_button1TrueCenter);
moveButtonAndSaveCenter(self.button2, CGPointMake(-100, 200), &_button2TrueCenter);
moveButtonAndSaveCenter(self.button3, CGPointMake(420, 200), &_button3TrueCenter);
}
}
Then in viewDidAppear:, animate them back to their original locations:
static void animateButton(UIButton *button, CGPoint newCenter, NSTimeInterval delay) {
[UIView animateWithDuration:.25 delay:delay options:0 animations:^{
button.center = newCenter;
} completion:nil];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if (animated) {
animateButton(self.button0, _button0TrueCenter, 0);
animateButton(self.button1, _button1TrueCenter, 0.2);
animateButton(self.button2, _button2TrueCenter, 0.4);
animateButton(self.button3, _button3TrueCenter, 0.6);
}
}
Assuming you have your buttons in an array, you could do something like this (your items should be in the correct end positions in the nib)
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
CGAffineTransform transform = CGAffineTransformMakeTranslation(0.f, -200.f);
[self.buttons enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) {
button.transform = transform; // This translates the view's off the top of the screen
[UIView animateWithDuration:0.25f
delay:0.25f * idx
options:UIViewAnimationCurveEaseOut // No point doing easeIn as the objects are offscreen anyway
animations:^{
button.transform = CGAffineTransformIdentity;
} completion:nil];
}];
}
This will animate every time. You may need to add an ivar to stop this happening and just set it to YES after this has run once. The problem I found when I was just messing around is that when it was calling viewDidAppear: animated was NO on first load, so I couldn't use that BOOL as a check
I've written a blog post about this subject: http://www.roostersoftstudios.com/2011/07/01/iphone-dev-performing-sequential-uiview-animations/
and I have a sample project there.
You can just chain the animations where when one finishes it calls the function of the next animation. Can you be more specific about the exact issues you are having?
I'm trying to implement an animation that happens when a user taps one of my tableview cells. Basically, the animation is just a little label with text like "+5" or "+1" that appears, then moves upwards whilst fading (basically like points appear in video games as the user scores them).
In the tableView:didSelectRowAtIndexPath: implementation of my controller, I'm doing the following (paraphrased for simplicity here):
CGRect toastFrame = /* figure out the frame from the cell frame here */;
UILabel *toast = [[UILabel alloc] initWithFrame:toastFrame];
toast.text = [NSString stringWithFormat:#"+%d", 5];
toast.backgroundColor = [UIColor clearColor];
toast.userInteractionEnabled = NO; // hoped this would work but it doesn't
[tableView addSubview:toast];
[UIView
animateWithDuration:1.0
animations:^
{
toast.alpha = 0.0;
toast.transform = CGAffineTransformMakeTranslation( 0.0, -44.0 );
}
completion:^ (BOOL finished)
{
[toast removeFromSuperview];
}];
[toast release];
The toast is appearing nicely and looks great. The problem is that until the animation completes, the tableview stops receiving touch events. This means that for one second after tapping a cell in the tableview, you can't tap any other cells in the tableview.
Is there a way to stop this from happening and allow the user to keep interacting with the tableview as if the animations weren't happening at all?
Thanks in advance for any help with this.
Another option may be to use animateWithDuration:delay:options:animations:completion: (untested, from the top of my head)
Take a look at the options parameter and the possible flags, defined by UIViewAnimationOptions. Included there is a flag called UIViewAnimationOptionAllowUserInteraction. This could be a solution, maybe you should try it out!
Have you tried doing it the other way? For example, after adding toast as a subview, you can do something like this:
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationCurve: UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration: 1.0];
toast.alpha = 0.0;
toast.frame.origin.y -= 44.0;
[toast performSelector:#selector(removeFromSuperview) withObject: nil afterDelay: 1.0];
[UIView commitAnimations];
and then release toast. You can try it this way and see if it works.
So I've got a problem with buttons and animations. Basically, I'm animating a view using the UIView animations while also trying to listen for taps on the button inside the view. The view is just as large as the button, and the view is actually a subclass of UIImageView with an image below the button. The view is a subview of a container view placed in Interface Builder with user interaction enabled and clipping enabled. All the animation and button handling is done in this UIImageView subclass, while the startFloating message is sent from a separate class as needed.
If I do no animation, the buttonTapped: message gets sent correctly, but during the animation it does not get sent. I've also tried implementing the touchesEnded method, and the same behavior occurs.
UIImageView subclass init (I have the button filled with a color so I can see the frame gets set properly, which it does):
- (id)initWithImage:(UIImage *)image {
self = [super initWithImage:image];
if (self != nil) {
// ...stuffs
UIButton *tapBtn = [UIButton buttonWithType:UIButtonTypeCustom];
tapBtn.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
[tapBtn addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
tapBtn.backgroundColor = [UIColor cyanColor];
[self addSubview:tapBtn];
self.userInteractionEnabled = YES;
}
return self;
}
Animation method that starts the animation (if I don't call this the button works correctly):
- (void)startFloating {
[UIView beginAnimations:#"floating" context:nil];
[UIView setAnimationDelegate:self];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
[UIView setAnimationDuration:10.0f];
self.frame = CGRectMake(self.frame.origin.x, -self.frame.size.height, self.frame.size.width, self.frame.size.height);
[UIView commitAnimations];
}
So, to be clear:
Using the UIView animation effectively disables the button.
Disabling the animation causes the button to work.
The button is correctly sized and positioned on screen, and moves along with the view correctly.
This resolves the issue:
[UIView animateWithDuration:20 delay: 0.0 options: UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionAllowUserInteraction
...
The animation is just eye candy. The animation lags behind the actual movement of the view. The button is already at the destination point when the animation starts. You just see a movie of the view/button moving.
If you want a button to be clickable during the animation, you'll have to make the animation yourself.
... was experiencing this same problem because my code was doing one large animation per block. I made an NSTimer based solution, like the one suggested above, and it worked... yet the movement was jerky (unless I inserted animation within every timer event trigger).
So, since animation was required anyway, I found a solution which requires no timer. It animates only a short distance and thus the button click is still accurate, with only a small error which is my case is very unnoticeable in the UI, and can be reduced depending on your params.
Note below that the error at any given time is < 15.0, which can be reduced for more accuracy depending on your animation speed requirements. You can also reduce the duration time for more speed.
- (void)conveyComplete:(UIView*)v
{
[self convey:v delay:0];
}
- (void)convey:(UIView*)v delay:(int)nDelay
{
[UIView animateWithDuration:.5
delay:nDelay
options:(UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction)
animations: ^
{
CGRect rPos = v.frame;
rPos.origin.x -= 15.0;
v.frame = rPos;
}
completion: ^(BOOL finished)
{
[self conveyComplete:v];
}];
}