[英]Detect which UIButton is pressed - UIImageView
我正在编写一个由2个UIImageViews和2个UIButton组成的简单应用程序。 UIImageViews放在UIButton的顶部。
我有1个UIImage出现在随机UIImageView上,并在2秒后消失。 然后,用户必须轻按他们认为图像出现在其上的按钮。
我将UIImageView数组改组,并使用第一个元素(索引0)显示图像。 当改组时,我跟踪哪个元素(即从哪个索引开始。可以说从索引“ n”开始)放置在数组的索引0上。
但是,当按下按钮时,我会将按下的按钮的ID与索引为n的按钮的ID进行比较。 (因为这是随机UIImageView的索引)。 但是由于某种原因,它不起作用。 :(
这是我的代码:(我没有上传.h文件。它仅包含声明。)下面的代码不会产生任何错误/警告消息。 它只是不输出我想要的结果。
@interface ViewController ()
@property (strong, nonatomic) NSMutableArray* tempButton;
@property (strong, nonatomic) NSMutableArray *tempViews;
@property (strong, nonatomic) UIImage *myImage;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_myImage = [UIImage imageNamed:@"hello"];
_tempButton = [[NSMutableArray alloc] initWithObjects:_button1, _button2, nil];
_tempViews = [[NSMutableArray alloc]initWithObjects:_image1, _image2, nil];
[self displayonView];
}
-(void)displayToFindSymbol{
[_toFindImage setImage:_myImage];
_toFindImage.contentMode = UIViewContentModeScaleAspectFit;
}
- (IBAction)pressed:(id)sender {
UIButton *result = (UIButton *)sender;
if (result == _tempButton[_correctButton]) {
NSLog (@"Correct");
}
else if (result != _tempButton[_correctButton]){
NSLog (@"Incorrect");
}
}
-(NSMutableArray *)shuffleViews{
NSUInteger count = _tempViews.count;
int n;
for (int i=count-1; i>=0; --i) {
n = arc4random() % (i + 1);
[_tempViews exchangeObjectAtIndex:n withObjectAtIndex:i];
}
_correctButton = n;
return _tempViews;
}
-(void)displayonView{
NSMutableArray *tempArray;
tempArray = [self shuffleViews]; // shuffle views
_correctImage = [tempArray objectAtIndex:0];
_correctImage.contentMode = UIViewContentModeScaleAspectFit;
[_correctImage setImage:_myImage];
NSTimer* myTImer;
myTImer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(hideLabel) userInfo:nil repeats:NO];
}
-(void) hideLabel{
_correctImage.hidden = YES;
for (UIButton *each in self.tempButton) {
each.enabled = YES;
}
[self displayToFindSymbol];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
您可以让每个按钮调用不同的方法作为选择器,或者为每个按钮分配不同的标记并在共享方法中检查它。
添加数组中的所有图像视图以及数组中的所有按钮。
将图像设置为随机图像视图时,请存储其索引,并在以后使用该索引来获取应单击的相应按钮。
伪代码
NSArray a = [NSArray arrayWithObjects:imgVie1,ImgView2...,nil]
// create second array with buttons
int randomIndex = arc4random() % a.count;
UIImageView *imgView = [a objectAtIndex:randomIndex];
//set image and hide later
UIButton *correctButton = [secondarray objectAtIndex:randomIndex];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.