开发者

How do I change NSString color?

I'm trying to make an app for the mac that has a user interface similar to an instant messenger. So far I have a text field, text view and a button, where everything is successfully connected in the App Delegate in IB. When you enter your text in the text field and press the button, it sends the string value to the text view and erases it in the text field. My problem is getting the users name to be a different color in the text view. For example, when I post something it should say in the text view "UserName: ...". I want the "UserName" to be a different color than the text he inserted.

So far I have a NSString *userName; and a NSString *userString; in my .h file. My method is to have the userName string to always be the same color and print it to text view before printing the userString. This is where I'm stuck, I've tr开发者_StackOverflow中文版ied to search the internet for answers but no luck.

So far I've tried,

userName = [NSDictionary dictionaryWithObjectsAndKeys:[NSColor redColor], NSBackgroundColorAttributeName, nil];

and

[userName setSelectedTextAttributes:
 [NSDictionary dictionaryWithObjectsAndKeys:
  [NSColor blueColor], NSBackgroundColorAttributeName, nil]];

under the the this code in the .m file

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification


NSString objects don't have attributes. You want an NSAttributedString. More specifically, you want controls that accept NSAttributedStrings with various ranges having different attributes. In your case, an NSTextView might be easier to use than an NSTextField.

Please read the documentation: Attributed String Programming Guide, NSTextView Class Reference, and Text System Overview before asking the inevitable "could you provide sample code, please?" :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜