gpt4 book ai didi

ios - 如何在 UIAlertView 的按钮中执行操作?

转载 作者:行者123 更新时间:2023-12-01 17:55:32 25 4
gpt4 key购买 nike

我有一个 UIAlertView从带有 2 个按钮的重新加载按钮 - 确定和取消。取消按钮工作正常,但是当我想在确定按钮中放置一些操作(再次玩游戏)时不起作用,除非该操作是 NSLog .

我的代码在 m 中。文件:

- (IBAction)startAgainAction:(id)sender {

UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Warning" message:@"Have you short that want start again the game?"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:@"Cancel", nil];

[alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

// My OK button

if (buttonIndex == alertView.cancelButtonIndex) {

// Action to start the game again... (don't work)
[self viewDidLoad];

} else if (buttonIndex == alertView.firstOtherButtonIndex) {

// NSLog it's accept but not other actions...
NSLog(@"Cancel");
}

}

是的,我放了 UIAlertViewDelegate h 中的协议(protocol)。文件

那么,为什么 viewDidLoad再次调用该方法时不起作用?

最佳答案

为了重新加载......你应该做一个

- (void)reloadGame {}

方法并手动重置所有内容。就像是:
- (void)reloadGame {
self.highScore = 0;
self.ballPosition = ...
// etc. depends on what you have
}

您也可以定义一些常量,这样您就不会对所有内容进行硬编码。并在 ViewDidLoad 和 reloadGame ...
- (void)viewDidLoad {
[super viewDidLoad];
[self reloadGame];
}

而不是同一个类有 2 个 .m 文件:
您应该使您的 popOver 类成为不同的类,并将其设置为您的游戏类:

在您的 popOver 类(class)中,您应该这样做:
@protocol CustomPopoverViewDelegate <NSObject>
- (void)doSomething;
// add other methods you need
@end

@interface CustomPopoverView : UIView
@property (nonatomic, retain) id <CustomPopoverView> delegate;

当您在游戏类中打开 popOver 时,您应该添加:
//popover init/alloc 
popover.delegate = self;
//show popover

还要确保你的游戏类监听 popover 委托(delegate)方法
#import "CustomPopoverView.h"
@interface GameViewClass : UIViewController <CustomPopoverViewDelegate>

并在您的 customPopover 类中的一个方法中,您想要转发到您刚刚放置的游戏类
- (void)methodNameForDoSomething {
if ([self.delegate respondsToSelector:@selector(doSomething)]) { //always nice to check. Notice this is the same doSomething we declared in .h in the protocol
[self.delegate doSomething];
}
}

和你将放置的游戏类
- (void)doSomething {
//whatever
}

你也可以发送参数

你也可以子类化......(当然popover是另一个拥有它自己的.h的类)

并将其声明为子类(您可以在创建新类时执行此操作并输入要子类化的类名,如下图所示)

enter image description here

并且您的弹出 View 的标题将如下所示:
@interface  CustomPopoverView : GameView

并且 GameView 的所有方法和属性都可用。

关于ios - 如何在 UIAlertView 的按钮中执行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18404135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com