selectText of NSTextField on focus

后端 未结 5 1685
既然无缘
既然无缘 2021-02-04 10:17

Could anybody suggest a method to select all the text of an NSTextField when the user clicks it?

I did find suggestions to subclass NSTextField

5条回答
  •  离开以前
    2021-02-04 10:56

    I know this is an old question, but here's an update for those who might stumble over this.

    Override NSTextField and hook into becomeFirstResponder(). You won't have to worry about managing delegates or clicks. The tricky part is finding the field editor for the focused text field first before asking it to select all the text.

    Objective-C

    // in AutoselectOnFocusTextField.h
    @interface AutoselectOnFocusTextField : NSTextField
    @end
    
    // in AutoselectOnFocusTextField.m
    @implementation AutoselectOnFocusTextField
    - (BOOL)becomeFirstResponder {
        if (![super becomeFirstResponder]) {
            return NO;
        }
        NSText* fieldEditor = [self currentEditor];
        if (fieldEditor != nil) {
            [fieldEditor performSelector:@selector(selectAll:) withObject:self afterDelay:0.0];
        }
        return YES;
    }
    @end
    

    Swift

    class AutoselectOnFocusTextField: NSTextField {
        override func becomeFirstResponder() -> Bool {
            guard super.becomeFirstResponder() else {
                return false
            }
            if let editor = self.currentEditor() {
                editor.perform(#selector(selectAll(_:)), with: self, afterDelay: 0)
            }
            return true
        }
    }
    

提交回复
热议问题