判断NSTextView和NSTextField的回车跟shift回车事件
OC代码
#pragma mark - NSTextFieldDelegate
- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector
{
if ([NSStringFromSelector(commandSelector) isEqualToString:@"insertNewline:"]) {
if (([NSApplication sharedApplication].currentEvent.modifierFlags & NSEventModifierFlagShift) != 0) {
NSLog(@"Shift-Enter detected.");[textView insertNewlineIgnoringFieldEditor:self];return YES;}else {
NSLog(@"Enter detected.");}}return NO;
}#pragma mark - NSTextViewDelegate
- (BOOL)textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector
{
//insertTab: -键入tab//insertNewline: -键入回车//deleteBackwardif ([NSStringFromSelector(commandSelector) isEqualToString:@"insertNewline:"]) {
if (([NSApplication sharedApplication].currentEvent.modifierFlags & NSEventModifierFlagShift) != 0) {
NSLog(@"Shift-Enter detected.");[textView insertNewlineIgnoringFieldEditor:self];return YES;}else {
NSLog(@"Enter detected.");return YES;}}return NO;
}
Swift代码
// MARK: - NSTextFieldDelegatefunc control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
if commandSelector == #selector(insertNewline(_:)) {
if let modifierFlags = NSApplication.shared.currentEvent?.modifierFlags, (modifierFlags.rawValue & NSEvent.ModifierFlags.shift.rawValue) != 0 {
print("Shift-Enter detected.")textView.insertNewlineIgnoringFieldEditor(self)return true} else {
print("Enter detected.")}}return false}// MARK: - NSTextViewDelegatefunc textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
if commandSelector == #selector(insertNewline(_:)) {
if let modifierFlags = NSApplication.shared.currentEvent?.modifierFlags, (modifierFlags.rawValue & NSEvent.ModifierFlags.shift.rawValue) != 0 {
print("Shift-Enter detected.")textView.insertNewlineIgnoringFieldEditor(self)return true} else {
print("Enter detected.")return true}}return false}
OC代码链接-NSTextViewNSTextField回车shift回车区分(oc)
Swift代码链接-NSTextViewNSTextField回车shift回车区分(swift)