正如标题所描述的,我按下按钮时能够添加声音,但我想知道是否有办法在按下相同的按钮时向主UIImageView添加图像更改。有没有办法将图片代码粘贴在" playFaceOfAudioType"方法提出?
到目前为止,这是我的代码:
#import "FourthViewController.h"
@interface FourthViewController ()
@end
@implementation FourthViewController
@synthesize audioPlayer;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (IBAction)facesAudioAction:(id)sender {
UIButton *btn=(UIButton *)sender;
[self playFaceAudioOfType:btn.tag];//Tag for button is set on the xib..
}
-(void)playFaceAudioOfType:(int)type{
[self stopAudio];
NSString *sound=@"";
switch (type) {
case 1:
sound=@"1";
break;
case 2:
sound=@"2";
break;
case 3:
sound=@"3";
break;
case 4:
sound=@"4";
break;
case 5:
sound=@"5";
break;
default:
break;
}
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:sound
ofType:@"mp3"]];
NSError *error;
if(url){
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(@"Error in audioPlayer: %@",
[error localizedDescription]);
} else {
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
}
[audioPlayer play];
}
}
-(void)stopAudio{
if(audioPlayer && [audioPlayer isPlaying]){
[audioPlayer stop];
audioPlayer=nil;
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
我从环顾四周了解到,通常这是通过执行if / else if类型的方法来完成的,但是想知道是否可以将它与switch语句位一起包含。
答案 0 :(得分:1)
您可以使用facesAudioAction
或playFaceOfAudioType
方法更改图片。
此外,您可以使用;
删除switch语句NSString *sound = [NSString stringWithFormat:@"%d", type];
您可以像这样设置图像;
NSString *imageName = [NSString stringWithFormat:@"%d.jpg", type];
yourImageView.image = [UIImage imageNamed:imageName];
答案 1 :(得分:-1)
如果您使用UIControl的标记,则在playFaceAudioOfType:function中定义NSString *sound = [NSString stringWithFormat:@"%d",type];
,然后您可以避免使用switch语句。
和Solution2,您可以使用setImage:forState:
方法显示按钮的样式,并使用button.titleLabel.text
保存它的歌曲信息(例如姓名)。