在NSString或nsmutablestring中不可能有多种颜色。我听说过一点NSAttributedString,它是在iPad SDK 3.2(或大约3.2)中引入的,并且在iPhone SDK 4.0 beta版中可用。

我想要一根有三种颜色的绳子。

我不使用3个独立的NSString的原因,是因为三个NSAttributedString子字符串的长度经常改变,所以我宁愿,不使用任何计算重新定位3个独立的NSString对象。

如果使用NSAttributedString是可能的,我怎么做以下-(如果不可能使用NSAttributedString,你会怎么做):

编辑: 记住,@"first", @"second"和@"third"随时会被其他字符串替换。所以使用硬编码的NSRange值是行不通的。

I am trying to make a simple Coffee Calculator. I need to display the amount of coffee in grams. The "g" symbol for grams needs to be attached to my UILabel that I am using to display the amount. The numbers in the UILabel are changing dynamically with user input just fine, but I need to add a lower case "g" on the end of the string that is formatted differently from the updating numbers. The "g" needs to be attached to the numbers so that as the number size and position changes, the "g" "moves" with the numbers. I'm sure this problem has been solved before so a link in the right direction would be helpful as I've googled my little heart out.

I've searched through the documentation for an attributed string and I even downloded an "Attributed String Creator" from the app store, but the resulting code is in Objective-C and I am using Swift. What would be awesome, and probably helpful to other developers learning this language, is a clear example of creating a custom font with custom attributes using an attributed string in Swift. The documentation for this is very confusing as there is not a very clear path on how to do so. My plan is to create the attributed string and add it to the end of my coffeeAmount string.

var coffeeAmount: String = calculatedCoffee + attributedText

其中calculatedCoffee是一个Int转换为字符串和“attributedText”是小写的“g”与自定义字体,我试图创建。也许我做错了。任何帮助都是感激的!