开发者

Is there a way to change color of just part of a string inside a UILabel?

Say I wanted to have the first six characters in black and the next six characters in开发者_如何学编程 blue, then the last 20 characters in black of a UILabel. Is this possible? Thanks!


In Big Cocoa you would use an NSAttributedString in a NSTextField or NSTextView. In Cocoa Touch you use a UIWebView to display rich text.


Zynga has done a lot of the heavy lifting for you on this one, check out Font Label on GitHub.


As Darren said, NSAttributedString is not supported on the iPhone but you could use a UIWebView.

Another possible solution might be to draw the text using NSString's -drawAtPoint:withFont: method (or similar). You could subclass UILabel and do the drawing in -drawRect:.

First, set the color to black and draw the first six characters. Note the width that -drawAtPoint:withFont: returns, and use it to calculate the starting point for the next six characters. Change the color, draw those characters, and then repeat the same for the remainder of the string.

Note that -drawAtPoint:withFont: doesn't do line breaks and stuff like that, so it could quickly get more complicated than what I've described.

Have a look at the NSString UIKit additions.


Give TTTAttributedString a try. It's a drop-in replacement for UILabel that renders NSAttributedStrings like a champ.


You want an NSAttributedString.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜