Question

I have a subclass of NSView named clickView as follows.

// clickView.h
@interface clickView : NSView {
    BOOL onOff;
}

- (BOOL)getOnOff;

// clickView.m
- (BOOL)getOnOff {
    return onOff;
}

- (void)mouseDown:(NSEvent *)event {
    if (onOff) {
        onOff = NO;
    } else {
        onOff = YES;
    }
    [self setNeedsDisplay:YES];
    NSLog(@"%@",self.identifier);
}

It utilizes its drawRect method (, which is not shown here,) to fill the rectangle with a color if the user clicks on it. And it uses a boolean value (onOff) to see if it's been clicked on. Now, switching to AppleDelegate, I instantiate this NSView subclass as follows.

// AppDelegate.m
- (IBAction)create4Clicked:(id)sender {    
    NSInteger rowCount = 10;
    NSInteger colCount = 10;
    NSInteger k = 1;
    for (NSInteger i2 = 0; i2 < rowCount; i2 ++) {
        for (NSInteger i3 = 0; i3 < colCount; i3 ++) {
            NSView *view = [[clickView alloc] initWithFrame:NSMakeRect(50+i2*10,50+i3*10,10,10)];
            [view setIdentifier:[NSString stringWithFormat:@"%li",k]];
            [view1 addSubview:view]; // view1 is NSView that's been created with Interface Builder
            k++;
        }
    }
}

So I now have 100 squares displayed on view1 (NSView). If I click on any of the squares, I do get its identifier. (See 'mouseDown.') Now, what I need to figure out is how to tell which square has its 'onOff' set to YES (or NO).

Thank you for your help.

Was it helpful?

Solution

A. First off all:

Probably you are new to Cocoa and Objective-C.

a. Why don't you use buttons?

b. onOff is obviously a property. Why don't you use declared properties?

B. To your Q:

You can retrieve the views with a specific state by asking the superview for its subviews and then filter them with a predicate:

NSPredicate *clickedPredicate = [NSPredicate predicateWithFormat:@"onOff == %d", YES];
NSArray* clickViews = [view1 subviews]; // Returns all subviews
clickViews = [clickViews filteredArrayUsingPredicate:clickedPredicate]; // On-views

But you should think about storing the state outside the views. What is your app for?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top