Iphone UIAlertView和确定单击的内容
我有一段代码,当用户在游戏结束时,它会提示他们是否想再次玩:Iphone UIAlertView和确定单击的内容,iphone,xcode,Iphone,Xcode,我有一段代码,当用户在游戏结束时,它会提示他们是否想再次玩: -(void)showAlert { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@" B U S T E D ! " message:@"Sorry, you busted!\n\nWant to try your luck 1 More Time! ?
-(void)showAlert
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@" B U S T E D ! "
message:@"Sorry, you busted!\n\nWant to try your luck 1 More Time! ?"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"New Game", nil];
[alert show];
[alert release];
}
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
// the user clicked one of the OK/Cancel buttons
if (buttonIndex == 0)
{
//here is where we can close it
}
if (buttonIndex == 1)
{
[self createNewGame];
}
}
现在我还想在用户首次启动应用程序时进行检查,查看是否存在以前的游戏文件,如果存在,询问他们是否希望继续。我知道我可以通过:
-(void)priorGameExists
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@" Previous Game Exists ! "
message:@"A previous game currently exists. Would you like to resume that game?"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Resumse", nil];
[alert show];
[alert release];
}
但是我如何让它转到一个新的“自定义”ClickedButtonIndex?我认为这与设置不同的委托有关,对吗?如果是这样的话,我该怎么做呢?您不一定需要另一名代表。阅读我对这个问题的回答:
Clicked Button Index
方法中,测试传入警报视图的标题
if ([actionSheet.title isEqualToString:@" B U S T E D ! "]) {
// do some busted stuff here
else if ([actionSheet.title isEqualToString:@" Previous Game Exists ! "]) {
// do some previous game stuff here
}
您可能希望使用静态字符串设置这些标题,因此代码中只有一个位置有字符串,但基本上就是这样做的。一个解决方案是将某些UIAlertView声明为私有类实例,如下所示:
@interface myViewControllerInterface : UIViewController {
@private
UIAlertView *newGameAlert;
UIAlertView *resumeGameAlert;
}
然后在视图控制器中,您可以使用它们创建AlertView:
-(void)showAlert {
newGameAlert= [[UIAlertView alloc] initWithTitle:@" B U S T E D ! "
message:@"Sorry, you busted!\n\nWant to try your luck 1 More Time! ?"
delegate:self cancelButtonTitle:@"Cancel"
otherButtonTitles:@"New Game", nil];
[newGameAlert show];
[newGameAlert autorelease];
}
-(void)priorGameExists {
resumeGameAlert = [[UIAlertView alloc] initWithTitle:@" Previous Game Exists ! "
message:@"A previous game currently exists. Would you like to resume that game?"
delegate:self cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Resumse", nil];
[resumeGameAlert show];
[resumeGameAlert autorelease];
}
最后,您可以使用每个警报视图的指针来区分它们:
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (actionSheet == newGameAlert ) {
//do something
} else if (actionSheet == resumeGameAlert ) {
//do something
}
}
您可以使用不同的委托,但更简单的方法是将
标记
属性设置为唯一值。如果标签是,比如说,10,你就会知道它来自原始警报,如果它是20,那么它将来自于原始警报。(当然,您可能应该使用常量。)答案似乎侧重于区分两个UIAlertView,这是解决您问题的一种方法,因此我投票将其作为副本关闭。如果您这样做,您应该在委托方法中将newGameAlert和resumeGameAlert设置为零,否则,您将有指向已发布对象的指针,这可能会造成危险。此外,Can Berk Güder的解决方案非常干净,不需要任何IVAR,而且非常漂亮。是的,我同意这一点,但我不知道这一点。直到现在我都是这样做的,但是现在我发现了这个新技术,我会用它。我们每天都在这里学习新事物啊。没有评论的反对票是怎么回事?特别是因为这个答案与Can Berk的答案几乎相同。虽然不那么优雅,但这并不是投反对票的理由。