Sta*_*ich 5 cocoa nsevent nstextview
我有基于NSTextView的组件,我想禁用它上面的单击,这样它的插入点不会受到这些单击的影响,但仍然能够为复制和粘贴工作选择文本片段:
我想要的正是我们默认的终端应用程序:有插入点,无法通过鼠标点击更改它,但仍然可以选择文本进行复制和粘贴.
我试过看- (void)mouseDown:(NSEvent *)theEvent方法,但没有找到任何帮助.
我找到了一种巧妙的解决方法来实现这种行为。我已经创建了演示项目,相关类有TerminalLikeTextView。这个解决方案工作完美,但我仍然希望有一个更好的解决方案:更少的 hacky 和更少的依赖 NSTextView 的内部机制,所以如果有人有这样的解决方案,请分享。
关键步骤是:
1) 在鼠标按下之前将 mouseDownFlag 设置为 YES,在按下鼠标后将 mouseDownFlag 设置为 NO:
@property (assign, nonatomic) BOOL mouseDownFlag;
- (void)mouseDown:(NSEvent *)theEvent {
self.mouseDownFlag = YES;
[super mouseDown:theEvent];
self.mouseDownFlag = NO;
}
Run Code Online (Sandbox Code Playgroud)
2) 防止插入点更新updateInsertionPointStateAndRestartTimer方法提前返回:
- (void)updateInsertionPointStateAndRestartTimer:(BOOL)flag {
if (self.mouseDownFlag) {
return;
}
[super updateInsertionPointStateAndRestartTimer:flag];
}
Run Code Online (Sandbox Code Playgroud)
3)前两步将使插入点不随鼠标移动,但selectionRange仍然会发生变化,因此我们需要跟踪它:
static const NSUInteger kCursorLocationSnapshotNotExists = NSUIntegerMax;
@property (assign, nonatomic) NSUInteger cursorLocationSnapshot;
#pragma mark - <NSTextViewDelegate>
- (NSRange)textView:(NSTextView *)textView willChangeSelectionFromCharacterRange:(NSRange)oldSelectedCharRange toCharacterRange:(NSRange)newSelectedCharRange {
if (self.mouseDownFlag && self.cursorLocationSnapshot == kCursorLocationSnapshotNotExists) {
self.cursorLocationSnapshot = oldSelectedCharRange.location;
}
return newSelectedCharRange;
}
Run Code Online (Sandbox Code Playgroud)
4) 如果需要,尝试使用按键恢复位置进行打印:
- (void)keyDown:(NSEvent *)event {
NSString *characters = event.characters;
[self insertTextToCurrentPosition:characters];
}
- (void)insertTextToCurrentPosition:(NSString *)text {
if (self.cursorLocationSnapshot != kCursorLocationSnapshotNotExists) {
self.selectedRange = NSMakeRange(self.cursorLocationSnapshot, 0);
self.cursorLocationSnapshot = kCursorLocationSnapshotNotExists;
}
[self insertText:text replacementRange:NSMakeRange(self.selectedRange.location, 0)];
}
Run Code Online (Sandbox Code Playgroud)