NSMatrix有多个切换按钮?

时间:2012-05-22 18:56:57

标签: objective-c cocoa multi-select nsmatrix nsbuttoncell

我正在尝试创建一个NSMatrix的{​​{1}},其中可以选择0到4个按钮(切换为开启)。我已经尝试了以下(测试)代码,但我不确定如何提供我需要的功能。也许用NSButtonCell是不可能的,我需要查看替代控件,或创建自己的控件?

NSMatrix

1 个答案:

答案 0 :(得分:1)

我得到了这个与NSMatrix的以下子类一起工作。我添加了一个属性onCount来跟踪处于打开状态的按钮数量:

@implementation RDMatrix
@synthesize onCount;

-(id) initWithParentView:(NSView *) cv {
    NSButtonCell *theCell = [[NSButtonCell alloc ]init];
    theCell.bezelStyle = NSSmallSquareBezelStyle;
    theCell.buttonType = NSPushOnPushOffButton;
    theCell.title = @"";
    if (self = [super initWithFrame:NSMakeRect(200,150,1,1) mode:2 prototype:theCell numberOfRows:4 numberOfColumns:4]){ 
        [self setSelectionByRect:FALSE];
        [self setCellSize:NSMakeSize(40,40)];
        [self sizeToCells];
        self.target = self;
        self.action = @selector(buttonClick:);
        self.drawsBackground = FALSE;
        self.autoresizingMask = 8;
        self.allowsEmptySelection = TRUE;
        self.mode = NSHighlightModeMatrix;
        self.onCount = 0;
        [cv addSubview:self];
        return self;
    }
    return nil;
}


-(IBAction)buttonClick:(NSMatrix *)sender {
    NSUInteger onOrOff =[sender.selectedCells.lastObject state];
    if (onOrOff) {
        self.onCount += 1;
    }else{
        self.onCount -= 1;
    }
    NSLog(@"%ld",self.onCount);
    if (self.onCount == 5) {
        [sender.selectedCells.lastObject setState:0];
        self.onCount -= 1;
    }    
}

当您尝试选择第5个按钮时,它会闪烁,但随后会熄灭。这可能是一个问题,具体取决于您使用这些按钮的状态。我只是用这种方法记录它们:

-(IBAction)checkMatrix:(id)sender {
    NSIndexSet *indxs = [self.mat.cells indexesOfObjectsPassingTest:^BOOL(NSButtonCell *cell, NSUInteger idx, BOOL *stop) {
        return cell.state == NSOnState;
    }];
    NSLog(@"%@",indxs);
}

编辑后:当我尝试单击第5个按钮时,我不喜欢我的第一个方法短暂闪烁按钮然后再次关闭按钮的方式。我发现我认为更好的解决方案涉及在矩阵子类中覆盖mouseDown(如果你想尝试这个,你应该删除setAction和setTarget语句并删除buttonClick方法):

-(void)mouseDown:(NSEvent *) event {
    NSPoint matPoint = [self convertPoint:event.locationInWindow fromView:nil];
    NSInteger row;
    NSInteger column;
    [self getRow:&row column:&column forPoint:matPoint];
    NSButtonCell *cell = [self cellAtRow:row column:column];
    if (self.onCount < 4 && cell.state == NSOffState) {
        cell.state = NSOnState;
        self.onCount += 1;
    }else if (cell.state == NSOnState) {
        cell.state = NSOffState;
        self.onCount -= 1;
    }
}