【发布时间】:2012-05-29 07:31:32
【问题描述】:
我正在尝试创建一个NSMatrix 的NSButtonCells,其中可以选择零到四个按钮(打开)。我尝试了以下(测试)代码,但不确定如何提供所需的功能。也许NSMatrix 不可能,我需要查看替代控件,或者创建自己的控件?
@interface MatrixView : NSView
{
NSScrollView *_scrollView;
NSMatrix *_matrixView;
}
@end
@implementation MatrixView
- (id)initWithFrame:(NSRect)frameRect
{
NSLog(@"initWithFrame. frameRect=%@", NSStringFromRect(frameRect));
self = [super initWithFrame:frameRect];
if (self != nil)
{
_scrollView = [[NSScrollView alloc] initWithFrame:NSMakeRect(0, 0, frameRect.size.width, frameRect.size.height)];
[_scrollView setBorderType:NSNoBorder];
[_scrollView setHasVerticalScroller:YES];
[_scrollView setHasHorizontalScroller:NO];
[_scrollView setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable];
NSSize contentSize = [_scrollView contentSize];
contentSize.height = 300;
// Make it 3 x however-many-buttons-will-fit-the-height
CGFloat gap = 8.0;
CGFloat width = (contentSize.width / 3.0) - (gap * 2.0);
NSUInteger rows = (contentSize.height / (width + gap));
NSLog(@"width=%f, rows=%lu", width, rows);
NSButtonCell *prototype = [[NSButtonCell alloc] init];
[prototype setTitle:@"Hello"];
[prototype setButtonType:NSToggleButton];
[prototype setShowsStateBy:NSChangeGrayCellMask];
_matrixView = [[NSMatrix alloc] initWithFrame:NSMakeRect(0, 0, contentSize.width, contentSize.height)
mode:NSListModeMatrix
prototype:prototype
numberOfRows:rows
numberOfColumns:3];
[_matrixView setCellSize:NSMakeSize(width, width)];
[_matrixView setIntercellSpacing:NSMakeSize(gap, gap)];
[_matrixView setAllowsEmptySelection:YES];
[_matrixView sizeToCells];
[_scrollView setDocumentView:_matrixView];
[self addSubview:_scrollView];
[self setAutoresizesSubviews:YES];
[prototype release];
}
return self;
}
...
【问题讨论】:
-
你当然可以拥有一个带有多个切换按钮的矩阵——我在 IB 中制作了一个,带有 NSButtonCells(推上推下类型)和高亮模式下的矩阵。这显示了在您再次按下它们之前一直突出显示的按钮。仅将其限制为 4 个,有点棘手 - 还没有完全弄清楚那个。
-
@rdelmar 我刚刚将上面的代码更改为使用按下按钮并将矩阵置于高亮模式,但它不能按预期工作(按下-push-off 模式被矩阵覆盖,没有任何东西被推入)。还有什么需要设置的吗?
标签: objective-c cocoa multi-select nsmatrix nsbuttoncell