在項目中我時常會遇到一些彈窗類提示,產(chǎn)品說讓它突然顯示太突兀了,我夸?一個嘴巴子,“你咋那么多事”。不過我心善就勉強接受他的建議加了點動畫,在此就用到下面的一些延時操作。
現(xiàn)階段我共知道四種能完成上述要求的方法:
1.NSObject方法
[self performSelector:@selector(delayMethod) withObject:nil afterDelay:1.0f];
主線程中執(zhí)行;
非阻塞的執(zhí)行方式;
可以通過cancelPreviousPerformRequestsWithTarget取消執(zhí)行。
2.定時器:NSTimer
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];
主線程執(zhí)行;
非阻塞的執(zhí)行方式;
可以通過NSTimer類的- (void)invalidate;取消執(zhí)行。
3.NSThread
[NSThread sleepForTimeInterval:1.0];
[self delayMethod];
主線程和子線程均可執(zhí)行;
一種阻塞的執(zhí)行方式,因此建議放在子線程中執(zhí)行;
暫時未有取消執(zhí)行的方法。
4.GCD
double delayInSeconds = 1.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
// 小提示此為延遲提交 不是延遲執(zhí)行
dispatch_after(popTime, dispatch_get_main_queue(), ^{
[self delayMethod];
});
通過參數(shù)選擇在主線程或子線程中執(zhí)行;
非阻塞的執(zhí)行方法;
暫時未有取消執(zhí)行的方法
DEMO
建議將該效果進行封裝,程序員要多心疼自己,少寫點是點0-0.
#pragma mark --移除活動規(guī)則View
- (void)removeRulesClick {
UIButton *button = [self.view viewWithTag:2222];
[UIView animateWithDuration:0.5 animations:^{
button.alpha = 0;
rulesView.alpha = 0;
}];
[self performSelector:@selector(removeRulesView) withObject:nil afterDelay:0.5f];
}
- (void)removeRulesView {
UIButton * button = [self.view viewWithTag:2222];
[button removeFromSuperview];
[rulesView removeFromSuperview];
}
總結(jié)完上面,突然感覺自己子線程這塊記憶有點模糊了,下一篇應(yīng)該會寫一點子線程方面的東西吧0_0。