Animation stops when scrolling in UIScrollView

2019-05-05 19:42发布

问题:

So I am trying to make a game where the user must scroll down as fast as they can in order to escape a "block" that grows infinitely bigger. Here is my problem: I am using a UI ScrollView as my mechanism for scrolling with a normal UI View as a subview. I have a time set to fire every 0.005 seconds that increases the height of both the "block" and the content height of the scroll view (so that the user can technically scroll infinitely). The problem is that whenever the user begins to scroll, this stops firing (i.e. the block stops getting taller). However, immediately when the user stops scrolling everything again works as it should. Here is all of the code that I have:

- (void)viewDidLoad {
[super viewDidLoad];
self.mainScrollView.delegate = self;
self.mainScrollView.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height * 2);


self.mainScrollView.backgroundColor = [UIColor greenColor];
self.mainScrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height * 10);
self.mainScrollView.scrollEnabled = YES;

self.darknessBlock.frame = CGRectMake(self.view.frame.origin.x,   self.view.frame.origin.y, self.view.frame.size.width, 100);
self.darknessBlock.backgroundColor = [UIColor blueColor];

[NSTimer scheduledTimerWithTimeInterval:0.005 target:self selector:@selector(increaseDarknessHeight) userInfo:nil repeats:YES];

}


-(void)increaseDarknessHeight{
int newHeight = self.darknessBlock.frame.size.height + 1;
self.darknessBlock.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.darknessBlock.frame.size.width, newHeight);
}

Any help as to why the block stops growing would be great! Sorry for the specific/simple question, I am somewhat new to this site and I am just looking around online for some help with this problem.

回答1:

You should add timer to another loop mode:

NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:0.005 target:self selector:@selector(increaseDarknessHeight) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

Updated for Swift:

let timer = Timer.scheduledTimer(timeInterval: 0.005, target: self, selector: #selector(increaseDarknessHeight), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: .common)