当前位置: 代码迷 >> 综合 >> Mac OS 开发 NSTextViewNSTextField回车shift回车区分(oc)(swift)
  详细解决方案

Mac OS 开发 NSTextViewNSTextField回车shift回车区分(oc)(swift)

热度:7   发布时间:2023-12-08 20:41:45.0

判断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)

  相关解决方案