我想知道是否可以将Alert View委托设置为其他ViewController。 原因是因为我打算根据用户按下的警报视图按钮实现某个动作。
以下是我要做的事情: -
1]在视图controller.h文件中声明<UIAlertViewDelegate>
,我需要实现alertView委托方法。
2]这就是我在appDelegate中声明alertView的方式。
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
{
alertView = [[UIAlertView alloc]initWithTitle:@"New Message" message:@"Click switch to check out" delegate:rosterListController cancelButtonTitle:@"OK" otherButtonTitles:@"Switch ", nil];
[alertView show];
}
}
3]现在我想在另一个View Controller中实现alertView委托方法clickedButtonAtIndex
,但它不会被调用。
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
NSLog(@"Cancel button pressed");
}
}
答案 0 :(得分:1)
您应该使AppDelegate成为AlertView委托,因为它是呈现Alter View的App Delegate。使用随机不相关的视图控制器是没有意义的。如果你有强烈的愿望,无论如何都要考虑你的设计和应用逻辑有问题。
或者,您可以创建一个新类,该类成为委托。此类的唯一目的是处理警报视图事件,并可能在演示者和警报视图之间传回数据并强制执行。您可以定义一个协议,该协议定义演示者必须满足的最小API,以便与委托处理程序进行通信。
对于呈现此警报视图的每个演示者,请为委托对象设置一个ivar。当您呈现警报视图时,无论哪个演示者,都要创建并初始化委托对象并将其设置为委托。当警报视图被解除时,释放委托对象。
请注意,委托对象可能需要对演示者的引用,以便处理解雇事件。
答案 1 :(得分:0)
在全球范围内设置rosterListController
委托,而不是将alertview委托设置为其rosterListController
委托。 Alertview delgate函数将在设置其委托的视图中调用。
GlobalSpace
id rosterDelegate;
+(void)setRosterDelegate:(id)_delegate{
_rosterDelegate=_delegat;
}
+(id)getRosterDelegate{
return _rosterDelegate;
}
现在,在您的rosterListController
班级中设置您的代表
[GlobalSpace setRosterDelegate:self];
和你的alertView一样
alertView = [[UIAlertView alloc]initWithTitle:@"New Message" message:@"Click switch to check out" delegate:[GlobalSpace getRosterDelegate] cancelButtonTitle:@"OK" otherButtonTitles:@"Switch ", nil];