我使用 uibuttons 创建了一个网格视图,现在需要在单击时选择和取消选择按钮。一切正常,但是当我尝试在单击按钮时播放声音时,应用程序通过在控制台中打印以下消息而崩溃:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIButton prepareToPlay]: unrecognized selector sent to instance 0x7526a20'
为了播放声音,我在 .h 文件中获取了 AVAudioPlayer claas 的对象并在视图中初始化它确实加载方法并在按钮单击时播放它,这是我的代码 .h 文件
#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioPlayer.h>
#import <AudioUnit/AudioUnit.h>
@interface PlayViewController : UIViewController<AVAudioPlayerDelegate>
{
IBOutlet UIButton *resetBtn;
UIButton *btn[25];
AVAudioPlayer *tapSound;
}
-(IBAction)reserBtnClkd;
@property(nonatomic,retain) AVAudioPlayer *tapSound;
@end
in .m file
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *path=[[NSBundle mainBundle] pathForResource:@"button-3" ofType:@"wav"];
AVAudioPlayer *Tapsound=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
self.tapSound=Tapsound;
[Tapsound release];
[pool release];
[self setTheIcons];
resetBtn.layer.cornerRadius=6.0;
resetBtn.backgroundColor=[UIColor colorWithRed:90/255.00 green:33.00/255.00 blue:179.00/255.00 alpha:1];
resetBtn.titleLabel.font=[UIFont fontWithName:@"Helvetica" size:22];
[resetBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}
#pragma mark
#pragma mark<Creating The Grid View Of Icons>
#pragma mark
-(void) setTheIcons
{
int x=11;
int y=55;
for(int i=1;i<=25;i++)
{
btn[i]=[UIButton buttonWithType:UIButtonTypeCustom];
btn[i].frame=CGRectMake(x, y, 58,58);
[btn[i] addTarget:self action:@selector(btnClkd:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn[i]];
if(i%5==0)
{
x=11;
y=y+60;
}
else
{
x=x+60;
}
}
[self reserBtnClkd];
}
-(void)btnClkd:(UIButton*)sender
{
sender.selected=!sender.selected;
if(sender.selected)
{
// UIView *tempView=[[UIView alloc]initWithFrame:CGRectMake(12, 12, 34, 34)];
UIView *tempView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 58, 58)];
tempView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"hover-effectNew.png"]];
tempView.userInteractionEnabled=NO;
[sender addSubview:tempView];
[tempView release];
}
else
{
NSArray *subviewToRemove=[sender subviews];
int i=1;
for(UIView *view in subviewToRemove)
{
if(i==2)
{
[view removeFromSuperview];
}
i++;
}
}
[self.tapSound prepareToPlay];
[self.tapSound setDelegate:self];
[self.tapSound play];
}
奇怪的是,只有当我在按钮单击方法上播放声音时,应用程序才会崩溃,否则如果我在视图中播放它确实加载了它就可以正常工作,抓了两天但找不到任何解决方案,请帮忙我