我在AppDelegate.m
中使用了LocalNotifications
如果用户打开了应用程序,则会以警报的形式发出通知。
AppDelegate.m
收到clickedButtonAtIndex
个活动。无论用户看到的当前视图如何,警报都会显示,到目前为止一切正常。
但是,在收到事件时,我想更改UIVIewController上存在的UISwitch的状态。
编辑:添加更多代码 我的应用程序以这种方式设置:
AppDelegate.m有这段代码:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
// Called from the local notification above when the View button is clicked and the app reopens
//called when app is open vs in background
NSLog(@"got notification");
UIApplicationState state=[application applicationState];
if(state==UIApplicationStateActive){
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Notice"
message:notification.alertBody
delegate:self cancelButtonTitle:@"Sleep"
otherButtonTitles:@"Turn Off", nil];
[alert show];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
NSLog(@"clicked button");
if(buttonIndex==1){
SettingsPage *setPage = [[SettingsPage alloc] initWithNibName:nil bundle:nil];
[setPage clickedAlert];
}
}
SettingsPage.m有以下代码:
@interface SettingsPage()
@property (weak, nonatomic) IBOutlet UISwitch *alarmSwitch;
@end
@implementation SettingsPage
-(IBAction)setAlarm{
//clear all notifications before setting a new one
[[UIApplication sharedApplication] cancelAllLocalNotifications];
//set a new LocalNotification
UILocalNotification *localNotification=localNotification =[[UILocalNotification alloc] init];
if(localNotification!=nil){
localNotification.fireDate=[NSDate dateWithTimeIntervalSinceNow:60]; //seconds
localNotification.timeZone=[NSTimeZone defaultTimeZone];
localNotification.alertBody=@"Reminder!";
localNotification.hasAction=YES; //fires didreceive event, opens app
localNotification.soundName=UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; }
}
-(void)clickedAlert{
NSLog(@"clicked alert");
[self.alarmSwitch setOn:NO animated:YES];
}
这具有将“alarmSwitch”设置为“Off”(从而取消更多通知)的预期效果,但是开关本身仍然在视图中显示为“On”(绿色)。
如何通过AppDelegate.m中的代码翻转SettingsPage上的实际开关,使其行为与用户执行相同(即更改视觉并执行连接方法)?
答案 0 :(得分:1)
正如CrimsonChris所说,你似乎每次都在创建一个新的SettingsPage实例,因此你没有看到你想要的改变。
您可以启动NSNotification,
[[NSNotificationCenter defaultCenter] postNotificationName:@"ClickedButtonAtIndex1" object:nil];
..并在你的UIViewController中听它。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleIndex1Clicked) name:@"ClickedButtonAtIndex1" object:nil];
使用你的UIViewController在选择器方法中执行它需要的东西:
-(void)handleIndex1Clicked
{
[self.setPage.alarmSwitch setOn:NO animated:YES];
}
PS。我建议让extern const NSStrings持有你的观察者名字。
希望有所帮助!
答案 1 :(得分:0)
您似乎正在获得新的SettingsPage
,然后将其alarmSwitch
设置为"关闭"。您可能想要的是获取现有的SettingsPage
,而不是使用alloc init创建一个新的。{/ p>