I am trying to loop through and programmatically make a grid of 256 NSButtons (16x16). The code I have so far is below. This is in Objective-C for my Mac app. So I am logging to see which tag I get when I click a button, but it keep returning the same tag every time.
I want it so that every button goes 1-256 from left to right, top to bottom. This code successfully makes them load into my view, but the tags are wrong.
#define N_ROWS 16
#define N_COLS 16
int btnSpaceDifference = 1;
int btnSpacing = N_ROWS + btnSpaceDifference;
for (int j = 0; j < N_ROWS; j++) {
for (int i = 0; i < N_COLS; i++) {
paintPixel = [[[NSButton alloc] initWithFrame:NSMakeRect(10 + (i * btnSpacing), 10 + (j * btnSpacing), 16, 16)] autorelease];
[paintPixel setTitle:@""];
[paintPixel setBezelStyle:NSBorderlessWindowMask];
[paintPixel setTag:j + i * N_ROWS + 1];
[paintPixel setAction:@selector(btnPaintAction:)];
[[[box.tabViewItems objectAtIndex:0]view] addSubview:paintPixel];
}
}
-(void)btnPaintAction:(id)sender{
NSLog(@"%ld", paintPixel.tag);
}
Not sure how its compiling, you might have paintPixel defined elsewhere. But you need to change your btnPaintAction from:
-(void)btnPaintAction:(id)sender {
NSLog(@"%ld", paintPixel.tag);
}
To something like this:
-(void)btnPaintAction:(id)sender {
NSButton * myButton = (NSButton *) sender;
NSLog(@"%ld", myButton.tag);
}