简体   繁体   中英

How to color a NSString or NSMutablearray and ad it to a UITextView

if I have a NSString or NSMubleArray like this:

NSString *p = @"Hello World";

how can I color Hello yellow, and world green?

And after I do this, I can add p to an UITextView and the textView visualize "Hello World" with the colors that I assigned before?

试试这个: https//github.com/AliSoftware/OHAttributedLabel这个项目解释了如何制作一个多色字符串。

You can not visually format an NSString object, and you cant change the color of individual words/characters in a UITextView or UITextField. If you want multi coloured text you'll have to format it in HTML/CSS and use a UIWebView :

NSString *p = @"<span style='color: yellow;'>Hello</span> <span style='color: green'>World</span>"; 
[myWebView loadHTMLString:p baseURL:nil];

(if you don't know CSS, you can use specific hex colors instead of the words green or yellow , eg #F00 = red (#RGB))

This is the way Apple suggest instead of using a UITextView, and it can work instead of UITextField as well.

我认为它通常不可能。一种方法是使用单独的标签并为该标签提供文本颜色。

You would have to subclass your own UITextView class. The default one only has one property for textColor, and it applies to the whole textview. Or you could go with two separate labels or textviews.

The bas news is that you can't. UIText view doesn't support attributed strings.

You are limited to webkit (see Jonathan.'s answer) or Core Text.

NSAttributedString and NSMutableAttributedString were recently added to iOS. If you don't want to use webkit, those are the correct and canonical objects to use. Core Text is mostly for drawing though, and doesn't have any convenient UI wrappers if you want the user to be able to edit the text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM