问题描述
我没有找到有关此问题的任何信息,我想知道是否可以通过按键盘上的空格键使NSTableView(或子类)选择行,并通过按上/下键浏览行而无需使用选择被重置。我想让nstableview像总指挥官的文件面板一样工作,如果有人在Windows下使用它的话。而且我什至都不知道从哪里开始。
I didn't find any information on this question, and I wonder if it is possible to make NSTableView (or subclass) to select rows by pressing space bar on keyboard, and navigate through rows by pressing up/down keys without the selection being reset. I want to make nstableview to behave like total commander's file panel, if someone used it under windows. And I don't even know where to start.
推荐答案
您将不得不创建NSTableView类的子类。这是基本的示例,您可以如何做。它使用空格键和鼠标右键来处理选择,但是它不能处理鼠标右键的拖动选择。
You will have to make subclass of the NSTableView class. This is basic example how you could do it. It handles selection with the spacebar and with the right mouse button, hoever it does not handle right mouse button drag selection.
该想法是在单选择模式下使用NSTableView,实施替代选择。我们添加属性 markedRows ,然后使用它代替原始的 selectedRows 属性。
The idea is to use NSTableView in single select mode and implement alternative selection. We add property markedRows and then use it instead of original selectedRows property.
FOTableView.h
#import <Cocoa/Cocoa.h>
@interface FOTableView : NSTableView
@property (strong,nonatomic) NSMutableIndexSet *markedRows;
@end
FOTableView.m
#import "FOTableView.h"
@implementation FOTableView
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
-(NSMutableIndexSet *) markedRows
{
if (!_markedRows) {
_markedRows = [NSMutableIndexSet new];
}
return _markedRows;
}
- (void)drawRow:(NSInteger)row clipRect:(NSRect)clipRect
{
if ([self.markedRows containsIndex:row]) {
NSRect clipRect = [self rectOfRow:row];
NSColor *color = [NSColor colorWithCalibratedRed:0.932 green:0.046 blue:0.960 alpha:1.000];
[color setFill];
NSRectFill(clipRect);
}
[super drawRow:row clipRect:clipRect];
}
- (void)keyDown:(NSEvent *)theEvent
{
NSString *keyString;
unichar keyChar;
keyString = [theEvent charactersIgnoringModifiers];
keyChar = [keyString characterAtIndex:0];
NSInteger row = [self selectedRow];
switch(keyChar){
case 32:
{
if (row != -1)
{
if ([self.markedRows containsIndex:row]) {
[self.markedRows removeIndex:row];
}
else {
[self.markedRows addIndex:row];
}
}
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:++row] byExtendingSelection:NO];
[self setNeedsDisplay:YES];
break;
}
default:
[super keyDown:theEvent];
}
NSLog(@"key pressed: (%hu)%@", keyChar,keyString);
}
- (void)rightMouseDown:(NSEvent *)theEvent
{
NSInteger row = [self rowAtPoint:[self convertPoint:[theEvent locationInWindow] fromView:nil]];
if ([self.markedRows containsIndex:row]) {
[self.markedRows removeIndex:row];
}
else {
[self.markedRows addIndex:row];
}
[self setNeedsDisplay:YES];
}
@end
这篇关于NSTableView通过按“空格”选择行。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!