【发布时间】:2016-03-16 22:33:00
【问题描述】:
我正在尝试在 UIAlertController 的标题中显示倒计时。我想要类似“您的会话将在 X 秒内到期”之类的内容。我的想法是创建一个 NSTimer 并将时间存储在 NSString stringWithFormat 中,并将该字符串作为警报控制器的标题。 这是我的倒计时方法:
@interface ViewController () {
NSString *seconds;
int mainInt;
NSTimer *timer;
}
- (void)countDown{
mainInt = 20;
mainInt -= 1;
seconds = [NSString stringWithFormat:@"%i", mainInt];
if (mainInt == 0) {
[timer invalidate];
}
}
这是由 IBAction 触发的 UIAlertController。触发时,控制器会以模态方式查看,并且标题显示“null seconds”,再等待几秒钟,然后尝试再次触发注销按钮,您会看到标题显示“19 seconds”。
- (IBAction)logout:(id)sender {
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
NSString *logOutString = [NSString stringWithFormat:@"%@ seconds.", seconds];
UIAlertController *alertController = [UIAlertController
alertControllerWithTitle:nil
message:logOutString
preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *cancelAction = [UIAlertAction
actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel action") style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
NSLog(@"Cancel Log out");
}];
UIAlertAction *okAction = [UIAlertAction
actionWithTitle:NSLocalizedString(@"log Out", @"Ok action") style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){
NSLog(@"Loged out");
//Log out code goes here
//When time is up, log out automatically
}];
[alertController addAction:okAction];
[alertController addAction:cancelAction];
[alertController setModalPresentationStyle:UIModalPresentationPopover];
[self presentViewController:alertController animated:YES completion:nil];
}
【问题讨论】:
标签: ios objective-c cocoa-touch