我有一个UITableViewController,它是RootViewController。它的 XIB 只有一个 TableView 。我通过 IB 添加了 UIActivityIndicator 并创建了 IBOutlet。我以编程方式向 RootViewController 添加了一个带有删除按钮的工具栏。当用户单击工具栏的删除按钮时,我想在屏幕中央显示指示器。下面的方法从数据库中删除数据,速度非常快。我想让用户知道发生了一些事情。如果我在没有 sleep() 的情况下运行下面的代码,它会很快并且我看不到指示器。但由于某些原因,我无论如何都看不到该指标。我猜 sleep() 会阻止重画?如果我取出 sleep() 和最后两行,我会看到指示器,但它当然永远不会消失。它还显示在窗口的左上角。
如何让下面的代码起作用,以便指示器至少显示 1/2 - 1 秒?
如何将指示器对齐在窗口中间?
[self.navigationController.view addSubview:activityIndicator];
[activityIndicator startAnimating];
[activityIndicator setNeedsDisplay];
//do something which might happen really fast
sleep(1); //create illusion
[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];
最佳答案
在您处理完事件并返回到运行循环之前,旋转器不会开始旋转。解决这个问题的方法是要求运行循环为您完成工作。
以下是我的意思的示例:
- (IBAction)deleteAction:(id)sender {
[self.navigationController.view addSubview:activityIndicator];
[activityIndicator startAnimating];
// Spinner won't start spinning until we finish processing this event, so
// we're just going to schedule the rest of what we need to do.
// doDelete: will run when the main thread gets its next event.
[self performSelectorOnMainThread:@selector(doDelete:)
withObject:record
waitUntilDone:NO];
// removeSpinner: will run in at least one second, but will wait if
// another event (like the doDelete: one) is in the middle of running.
[self performSelector:@selector(removeSpinner:)
withObject:activityIndicator
afterDelay:1.0];
}
- (void)doDelete:(id)record {
[record delete]; // or whatever it is you need to do
}
- (void)removeSpinner:(UIActivityIndicator*)activityIndicator {
[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];
}
注意:此代码中没有任何内容可以保证阻止它在“ sleep ”期间处理其他触摸,因此请确保以某种方式锁定其他事件。
关于iphone - 显示 UIActivityIndicator x 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/605311/