簡體   English   中英

檢測按下了哪個UIButton-UIImageView

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM