Search code examples
ios8nstimeruialertcontrolleruialertaction

Why does the title of the UIAlertController not get updated?


After displaying the UIAlertController I start a timer which calls timerLabel. This should update the UIAlertControllers only action title. The NSLog displays that the title is actually changing from 25 down to 1. However the actual title on the UIAlertController continues to show "25".

Do I have to call anything to update the title so it can be displayed? When I run exact code on 8.3 it works however thats beta and may mean it won't work when actually released so I need it to work on non beta 8.2 too. Appreciate any suggestions.

NSTimer *buttonTimer;
UIAlertController *touchAdverts;
int timeStart;



-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];

timeStart = 25;
//inform user they need to touch adverts

touchAdverts = [UIAlertController alertControllerWithTitle:@"IMPORTANT" message:@"text to show user" preferredStyle:UIAlertControllerStyleAlert];
[touchAdverts addAction:[UIAlertAction actionWithTitle:[NSString stringWithFormat:@"%i",timeStart] style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//invalidate timer when button pressed
[buttonTimer invalidate];
[[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"hasHadTimedAlert"];
[[NSUserDefaults standardUserDefaults]synchronize];
}]];

//disables the action button from being interated with
[touchAdverts.actions[0]setEnabled:NO];
if ( ![[NSUserDefaults standardUserDefaults]boolForKey:@"hasHadTimedAlert"]) {
[self.view.window.rootViewController presentViewController:touchAdverts animated:YES completion:^{
//when alert is shown start timer to update the title of the alerts action
buttonTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerLabel) userInfo:nil repeats:YES];
}];
}



}


-(void)timerLabel{

if (timeStart >0) {
//countdown from timeStart
timeStart  -= 1;
//update the action button title each second to new timeStart value
[touchAdverts.actions[0] setTitle:[NSString stringWithFormat:@"%i",timeStart]];
NSLog(@"%@",[touchAdverts.actions[0] title]);
}else{
//When value of timeStart reaches 0 enable the action button and change title
[touchAdverts.actions[0] setEnabled:YES];
[touchAdverts.actions[0] setTitle:@"I have read & understood the above"];
}

}

Solution

  • Currently, you can't modify an alert controller's view's visible title once the view has been displayed (though it sounds from your experiments as if this will start working in iOS 8.3 when it goes final). But you don't really need to, since it is easy to write your own view controller with your own view that looks and behaves like an alert view controller's view. When you do that, you are in complete control of the interface. So if you want this to work in iOS 8.2 and before, that's what I would suggest doing.