简体   繁体   中英

How do I get my NSTextView to respond properly to the Home and End keys?

Apple makes NSTextView respond to page up, page down, arrow keys, etc. automatically, but the home and end keys are not automatically handled by NSTextView out of the box. There's no apparent reason for this; I just logged a Radar on it. Until they fix that Radar, the question is: how do I make my NSTextView handle those keys correctly?

I just spent a little while googling around about this, and didn't find a good modern answer on either SO or elsewhere, so I'm posting my own answer here just for other's reference.

The wrong way to do this is to implement keyDown: and check for the particular keys having been pressed. This circumvents Apple's key-binding mechanism, which as it happens does supply the needed selectors for the concepts of "scroll to beginning" and "scroll to end"; NSTextView just doesn't respond to those selectors.

All you need to do is to add, in your NSTextView subclass, the following:

- (void)scrollToBeginningOfDocument:(id)sender
{
    [self scrollRangeToVisible:NSMakeRange(0, 0)];
}
- (void)scrollToEndOfDocument:(id)sender
{
    [self scrollRangeToVisible:NSMakeRange([[self string] length], 0)];
}

This hooks up the NSResponder methods for the relevant key bindings to appropriate actions in your NSTextView. These methods on NSResponder appear to have been public since 10.6 or so, and may have actually existed for a while before that, so this solution should be good on all modern systems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM