Mac os键盘和鼠标监听支持,也是在NSView
层级别进行监听。
例如我现在需要监听TableView
的鼠标邮件删除或者选择行后点击键盘delete
。
所以第一步写Window
下的TableView
实现。
直接贴代码
typedef NS_ENUM(NSUInteger, FileTableViewKeyType) {
FileTableViewKeyTypeEnterCharacter = NSEnterCharacter,
FileTableViewKeyTypeBackspaceCharacter = NSBackspaceCharacter,
FileTableViewKeyTypeTabCharacter = NSTabCharacter,
FileTableViewKeyTypeNewlineCharacter = NSNewlineCharacter,
FileTableViewKeyTypeFormFeedCharacter = NSFormFeedCharacter,
FileTableViewKeyTypeCarriageReturnCharacter = NSCarriageReturnCharacter,
FileTableViewKeyTypeBackTabCharacter = NSBackTabCharacter,
FileTableViewKeyTypeDeleteCharacter = NSDeleteCharacter,
FileTableViewKeyTypeLineSeparatorCharacter = NSLineSeparatorCharacter,
FileTableViewKeyTypeParagraphSeparatorCharacter = NSParagraphSeparatorCharacter
};
@protocol FileTableViewEventDelegate <NSObject>
@optional
- (void)tableView:(NSTableView *)tableView didClickDownAtKeyType:(FileTableViewKeyType)keyType indexSet:(NSIndexSet *)indexSet;;
- (void)tableView:(NSTableView *)tableView didClickDeleteAtIndexSet:(NSIndexSet *)indexSet;
@end
@interface FileTableView : NSTableView
@property (nullable, weak) id <FileTableViewEventDelegate> eventDelegate;
@end
#import "FileTableView.h"
@interface FileTableView()
@end
@implementation FileTableView
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
// Drawing code here.
}
- (void)keyDown:(NSEvent *)event {
unichar character = [[event characters] characterAtIndex: 0];
if([self.eventDelegate respondsToSelector:@selector(tableView:didClickDownAtKeyType:indexSet:)]) {
[self.eventDelegate tableView:self didClickDownAtKeyType:character indexSet:[self selectedRowIndexes]];
}
}
- (NSMenu *)menuForEvent:(NSEvent *)event {
if (event.type == NSEventTypeRightMouseDown) {
NSPoint menuPoint = [self convertPoint:[event locationInWindow] fromView:nil];
NSInteger row = [self rowAtPoint:menuPoint];
NSIndexSet *indexSet = [self selectedRowIndexes];
if (row == -1 || [indexSet count] == 0) {
return nil;
}
if ([indexSet containsIndex:row]) {
NSMenu *menu = [[NSMenu alloc] initWithTitle:@"Custom"];
NSMenuItem *deleteItem = [[NSMenuItem alloc] initWithTitle:@"Delete" action:@selector(deleteAction:) keyEquivalent:@""];
[menu addItem:deleteItem];
return menu;
}
return nil;
}
return nil;
}
- (void)deleteAction:(NSMenuItem *)item {
NSIndexSet *indexSet = [self selectedRowIndexes];
if([self.eventDelegate respondsToSelector:@selector(tableView:didClickDeleteAtIndexSet:)]) {
[self.eventDelegate tableView:self didClickDeleteAtIndexSet:indexSet];
}
}
@end
网友评论