I’m working on a Cocoa text editor which uses an NSTextView. Is it possible to change the color of certain portions of the text?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You should add your controller as the delegate of the
NSTextStorageobject of theNSTextView([textView textStorage]) and then implement the delegate method‑textStorageDidProcessEditing:. This is called whenever the text changes.In the delegate method you need to get the current
NSTextStorageobject from the text view using the-textStoragemethod ofNSTextView.NSTextStorageis a subclass ofNSAttributedStringand contains the attributed contents of the view.Your code must then parse the string and apply coloring to whatever ranges of text are interesting to you. You apply color to a range using something like this, which will apply a yellow color to the whole string:
How you parse the text is up to you.
NSScanneris a useful class to use when parsing text.Note that this method is by no means the most efficient way of handling syntax coloring. If the documents you are editing are very large you will most likely want to consider offloading the parsing to a separate thread and/or being clever about which sections of text are reparsed.