如何将Nview中的现有按钮分配给数组

时间:2010-12-18 22:45:07

标签: arrays xcode button

我需要帮助在xcode中制作一个数组,以收集一个窗口(NView)中的25个现有按钮,例如,当按下一个按钮时,更改背景颜色或其他按钮的标题。

感谢。

这是代码:

Botones.h

#import <Cocoa/Cocoa.h>

extern const NSString* Nivel[];
extern const NSString* Ayuda[];
extern const NSString* Boleo[];
BOOL Estado[5][5];
int Columna;
int Fila;
//NSColor* Rojo = (NSColor *)redColor;

@interface Botones : NSObject {
    IBOutlet id Intents;
    IBOutlet id Nivel;
    IBOutlet id BoxBot;
    NSArray *Arbot;
}

- (IBAction)OrBoton:(id)sender;

Botones.m

#import "Botones.h"

const NSString *Nivel[] = {@"101214",@"0002040507091517192202224",@"01030506080910111314151618192123"};
BOOL Estado[5][5] = {FALSE};
int Columna = 0;
int Fila = 0;


@implementation Botones
- (void)awakeFromNib {
Arbot = [[BoxBot subviews] copy];
}

- (IBAction)OrBoton:(id)sender {
    [Intents setIntValue:[sender tag]]; 
    Columna =[sender tag] % 5;
    Fila = [sender tag] / 5;
    if (Estado[Columna][Fila] == FALSE) {
        Estado[Columna][Fila] = TRUE;
        [sender setTitle:@"OK"];
        //[sender setBackgroundColor:[NSColor redColor]];
         }
    else {
        Estado[Columna][Fila] = FALSE;
        [sender setTitle:@""];
        //[sender setBackgroundColor:[NSColor greenColor]];

    }
    if (Fila > 0) {   
        if (Estado[Columna][Fila - 1] == FALSE) {
            Estado[Columna][Fila - 1] = TRUE;
            NSLog(@"%@",[BoxBot subviews]);
            [[Arbot objectAtIndex:5] setTitle:@"OK"];// <-- Don't changes button's title                
    }
}
}   

1 个答案:

答案 0 :(得分:0)

如果按钮是视图中唯一的子视图,则可以使用:

//view is a variable pointing to the view containing the buttons
NSArray *buttons = [[view subviews] copy];

如果视图中还有其他视图,则必须将其过滤掉:

//view is a variable pointing to the view containing the buttons
NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:25];
for(NSView *v in [view subviews]) {
    if([v isKindOfClass:[NSButton class]]) [buttons addObject:v];
}

修改

...
@interface Botones : NSObject {
    IBOutlet id Intents;
    IBOutlet id Nivel;
    IBOutlet id BoxBot;
    NSArray *ArBot;
}
...

Botones.m

...
@implementation Botones
- (void)awakeFromNib {
    ArBot = [[BoxBot subviews] copy];
    /*or
    NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:25];
    for(NSView *v in [BoxBot subviews]) {
        if([v isKindOfClass:[NSButton class]]) [array addObject:v];
    }
    ArBot = [array copy];
    [array release];*/
}
...