FREN

#FF00AA


28 fév. 2009

Changing the selected text’s color for an NSTextField

Yeah, I’m getting intimate with Cocoa development, so you can expect occasional posts like this one. My readers are not supposed to care about this; I’m just posting it because I’ve been googling that question for an hour and didn’t find a proper answer anywhere.

 

There’s a point in the Cocoa documentation (I would link to it, but it looks like URLs tend to change every so often) that says:

A text field allows you to set the attributes of its text, the text background color, whether it draws the background, and whether it draws a bezel or border around its text. Note that the text and background colors of selected text are configurable. The selected text color overrides any actual text color applied to the text while it’s selected (this is generally the case with controls).

But nowhere does it say how. NSTextView has a setSelectedTextAttributes, but NSTextField doesn’t; so how do you change the selected text’s attributes?

Maybe you’re supposed to know that from the start (I’m learning Cocoa in random order, by googling for bits of information as I need them, and I know that’s not how you’re supposed to do it but, hey, my app works, and it doesn’t even seem to leak), but NSTextView isn’t just a control you can drop in Interface Builder to let users enter long, formatted text; there’s also an NSTextView associated with each window, and it processes the text behind the scenes or something.

So all you have to do is get access to that NSTextView, and setSelectedTextAttributes on it. Here’s how you get text fields of the window InputWindow to show selected text on a black background:

NSTextView *textEditor = (NSTextView *)[InputWindow fieldEditor:YES forObject:InputTextField];

[textEditor setSelectedTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSColor blackColor], NSBackgroundColorAttributeName, nil]];

The (NSTextView*) bit is because fieldEditor:forObject: thinks it returns an NSText*, even though it seems like it does return an NSTextView* — otherwise the code just wouldn’t work, would it? Looks like a known bug in the Cocoa headers.

Vous voulez savoir quand je poste du contenu sur mon blog ? Il suffit de vous inscrire gratuitement à un agrégateur RSS (Feedly, NewsBlur, Inoreader, …) et d'ajouter www.ff00aa.com à vos flux (ou www.garoo.net pour vous abonner à tous les sujets). On n'a pas besoin de newsletters, pas besoin de Twitter, le RSS existe toujours.

Mentions légales : ce blog est hébergé par OVH, 2 rue Kellermann, 59100 Roubaix, France, www.ovhcloud.com.

Les données des visiteurs de ce blog ne sont pas utilisées ni transmises à des tiers. Les posteurs de commentaires peuvent demander leur suppression par e-mail.

Tous contenus © de l'auteur ou couverts par le droit de citation.