按钮按iOS中的特定顺序按下

时间:2014-10-15 11:43:31

标签: ios xcode button

我想用for按钮创建一个UIViewController。我希望用户按下具有特定顺序的四个按钮。我到目前为止所做的是我在每个按钮中给出一个随机标签号码,代码如下:

-(void)prepareArray {
self.arary = [[NSMutableArray alloc]init];
while (self.arary.count <4) {
    int value = arc4random()%4;
    BOOL isFound = [[self.arary filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"intValue == %d",value]]] count];
    if(!isFound)
        [self.arary addObject:[NSNumber numberWithInteger:value]];
}
NSLog(@"%@", arary);
button1.tag = [[arary objectAtIndex:0]intValue];
button2.tag = [[arary objectAtIndex:1]intValue];
button3.tag = [[arary objectAtIndex:2]intValue];
button4.tag = [[arary objectAtIndex:3]intValue];

所以我的问题是:如何创建一个方法,我按下0到3的按钮顺序?我试着用case和if语句来解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

-(IBAction)buttonPressed:(UIButton *)button{

[clickDictionary setObject:[NSString stringWithFormat:@"%d",button.tag] forKey:button.titleLabel.text];
NSLog(@"clickDictionary : %@", clickDictionary);

}

您可以按上述方法编写方法。每按一次按钮都会调用此方法。 在clickDictionary中,您将获得按钮名称及其标记。 您可以根据需要对此词典进行排序。

答案 1 :(得分:0)

我用以下方法解决了我的问题。首先,我用for循环创建我的按钮:

for (int count = 0; count < 4; count++)
{
    self.theButtons = [UIButton buttonWithType:UIButtonTypeSystem];
    self.theButtons = [[UIButton alloc] initWithFrame:CGRectMake(100, y, 100, 40)];
    [self.theButtons setTitle:[NSString stringWithFormat:@"Press Me"] forState:UIControlStateNormal];
    [self.theButtons setTag:[[data.randomArray objectAtIndex:count]intValue]];
    [self.theButtons addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.theButtons setBackgroundColor:[UIColor purpleColor]];
    [self.buttonArray addObject:theButtons];
    [self.view addSubview:theButtons];
    y=y+60;
}

并附上按钮的标签:

self.randomArray = [[NSMutableArray alloc]init];
while (self.randomArray.count <4) {
    int value = arc4random()%4+1;
    BOOL isFound = [[self.randomArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"intValue == %d",value]]] count];
    if(!isFound)
        [self.randomArray addObject:[NSNumber numberWithInteger:value]];
}

最后,如果我想检查用户按下按钮的顺序,我会创建另一个数组:

- (void)buttonClicked:(UIButton*)button
    {
        NSLog(@"Button %ld clicked.", (long int)[button tag]);
        int value = [button tag];
        button.hidden = YES;
        [buttonArray removeObject:button];
        //When user taps a button another array created which stores the button tags
        if([addIntArray indexOfObject:[NSNumber numberWithInt:value]] == NSNotFound) {
            [addIntArray addObject:[NSNumber numberWithInt:value]];
    }

并将其按钮单击与静态数组进行比较。