How to handle NSTextView preferences (spelling and

2019-05-10 06:37发布

The NSTextView class allows the user to dis-/enable features like "spelling while typing" with the context menu (right click). But when I use a NSTextView in my own app, those preferences are not saved automatically by the text view itself, which means that I have to save them separately - right?

Now I also want to allow the user to change those settings in my app preferences (like in TextEdit). What I do is to save the text view preferences in the user defaults, which means that every time the user changes the setting in the app preferences, I apply those settings and save them. It's pretty easy to accomplish that except the one case where the user changes the text view setting with the context menu and not through the app preferences.

My question now: How can I get notified when the settings of a NSTextView is changed, so I can save them?

2条回答
▲ chillily
2楼-- · 2019-05-10 06:42

You could also use NSTextViews method toggleAutomaticSpellingCorrection:

This method is only called, when the user changes the setting via menu/contextMenu and not if the programmer changes the setting programatically (e.g. temporarily disabling when inserting text).

查看更多
Anthone
3楼-- · 2019-05-10 07:01

I've done a project where I have subclassed NSTextView and I can easily catch any setting changes that have been made by the user.

So, for you to do this, simply create a new .h & .m file and declare it like this:

(in the .h file)

@interface BrutellaTextView : NSTextView

@end

(in the .m file)

@interface BrutellaTextView

- (void)setContinuousSpellCheckingEnabled:(BOOL)flag
{
    // here I am just setting user defaults... you may choose
    // to have some other place to save the settings
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    if(userDefaults)
    {
        [userDefaults setBool: flag forKey: @"continuousSpellCheckingEnabled"];
    }

    // and to get the functionality to actually happen, 
    // call the superclass
    [super setContinuousSpellCheckingEnabled: flag];
}

@end

(and you can override other NSTextView methods to capture when other settings change, such as setRulerVisible:).

Now, when you are in your XIB file, make sure to set the CustomClass of your text view to be BrutellaTextView and you'll be all set!

There are no notifications that you can register to get NSTextView settings changes, so as far as I'm concerned, this is the best way to do what you're trying to do.

I hope this answer helps you out!

查看更多
登录 后发表回答