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”与自定义字体,我试图创建。也许我做错了。任何帮助都是感激的!


当前回答

使用这个示例代码。这是满足您需求的非常短的代码。这对我很有用。

let attributes = [NSAttributedStringKey.font : UIFont(name: CustomFont.NAME_REGULAR.rawValue, size: CustomFontSize.SURVEY_FORM_LABEL_SIZE.rawValue)!]

let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)

其他回答

在beta 6中工作良好

let attrString = NSAttributedString(
    string: "title-title-title",
    attributes: NSDictionary(
       object: NSFont(name: "Arial", size: 12.0), 
       forKey: NSFontAttributeName))

Swift: xcode 6.1

    let font:UIFont? = UIFont(name: "Arial", size: 12.0)

    let attrString = NSAttributedString(
        string: titleData,
        attributes: NSDictionary(
            object: font!,
            forKey: NSFontAttributeName))
 let attrString = NSAttributedString (
            string: "title-title-title",
            attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])

斯威夫特有一个非常甜蜜的方式来做到这一点,真的不需要任何工作。只需提供应该匹配的模式以及应用于它的属性。它们在很多方面都很有用,去看看吧。

``` Swift
let defaultGenreText = NSAttributedString(string: "Select Genre - Required")
let redGenreText = defaultGenreText.applying(attributes: [NSAttributedString.Key.foregroundColor : UIColor.red], toRangesMatching: "Required")
``

如果你有多个地方,这将被应用,你只希望它发生在特定的实例,那么这个方法将不起作用。

你可以一步完成,只是分开时更容易阅读。

我创建了一个在线工具来解决你的问题!你可以编写字符串并以图形化的方式应用样式,该工具会给你objective-c和swift代码来生成字符串。

Also是开源的,所以请随意扩展它并发送pr。

变压器的工具

Github