我如何一次运行我的代码。也就是说,我有一个你想要一致执行的代码。例:
- (IBAction)downloadPressed:(id)sender {
//1
CGRect frameDelete = deleteButton.frame;
frameDelete.origin.y = (deleteButton.frame.origin.y-50);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration: 0.5];
deleteButton.frame = frameDelete;
[UIView commitAnimations];
[progressLine setProgress:0];
//2 Wait until the code is executed above, and then run the code below
NSURL *fileURL = [NSURL URLWithString:@"http://intercreate.ru/all.zip"];
[self downloadDataAtURL:fileURL];
//3 Wait until the code is executed above, and then run the code below
CGRect frameDelete1 = deleteButton.frame;
frameDelete1.origin.y = (deleteButton.frame.origin.y+50);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration: 0.5];
deleteButton.frame = frameDelete1;
}
也就是说,我希望我的代码分为三个部分:
- 第一个向上移动旋钮
- 下载文件
- 后退按钮。
我该怎么做?
做这样的事情的传统方法是协议/委托设计模式。但是,由于块,这已经过时了。它们是实现这一目标的最简单方法。例如,它们内置于出色的MBProgressHUD中。你可以用这个完成你想要的:
- (IBAction)downloadPressed:(id)sender {
CGRect frameDelete = deleteButton.frame;
frameDelete.origin.y = (deleteButton.frame.origin.y-50);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration: 0.5];
deleteButton.frame = frameDelete;
[UIView commitAnimations];
[progressLine setProgress:0];
MBProgressHUD *aHud = [[MBProgressHUD alloc] initWithView:self.view];
[aHud showHudAnimated: NO whileExecutingBlock:^
{
//2 Wait until the code is executed above, and then run the code below
NSURL *fileURL = [NSURL URLWithString:@"http://intercreate.ru/all.zip"];
[self downloadDataAtURL:fileURL];
} completionBlock: ^
{
//3 Wait until the code is executed above, and then run the code below
CGRect frameDelete1 = deleteButton.frame;
frameDelete1.origin.y = (deleteButton.frame.origin.y+50);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration: 0.5];
deleteButton.frame = frameDelete1;
[UIView commitAnimations];
}];}
进度HUD可以做更多的事情,例如显示进度指示器:)
查看这篇文章以了解块的使用:链接
前半部分可能会随着较新的基于块的动画而下降,您可以提供一段在动画完成后执行的代码。第二部分我肯定会使用通知来做,您可以在文件下载完成后发布通知,然后代码的任何其他部分都可以以他们想要的任何方式响应此事件,更改 GUI,通知用户,删除要下载的内容列表,您还可以添加新内容来收听此通知而无需更改原始代码。
您似乎正在使用旧式beginAnimations
commitAnimations
方法。
如果迁移到新的基于块的动画方法,则可以使用完成处理程序块,如果使用异步 URL 下载方法,API 还提供了添加完成块的位置。
所以,本质上:
- 创建基于块的动画以移动按钮
- 在此动画的完成处理程序中触发异步下载
- 在下载的完成处理程序中,触发一个动画来移动按钮。
由于这些都在一个基于块的方法(原始动画块)中,因此各个操作将一个接一个地发生。