How do I make an attributed string using Swift?

前端 未结 28 2164
耶瑟儿~
耶瑟儿~ 2020-11-22 10:11

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 usin

28条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 10:57

    I would highly recommend using a library for attributed strings. It makes it much easier when you want, for example, one string with four different colors and four different fonts. Here is my favorite. It is called SwiftyAttributes

    If you wanted to make a string with four different colors and different fonts using SwiftyAttributes:

    let magenta = "Hello ".withAttributes([
        .textColor(.magenta),
        .font(.systemFont(ofSize: 15.0))
        ])
    let cyan = "Sir ".withAttributes([
        .textColor(.cyan),
        .font(.boldSystemFont(ofSize: 15.0))
        ])
    let green = "Lancelot".withAttributes([
        .textColor(.green),
        .font(.italicSystemFont(ofSize: 15.0))
    
        ])
    let blue = "!".withAttributes([
        .textColor(.blue),
        .font(.preferredFont(forTextStyle: UIFontTextStyle.headline))
    
        ])
    let finalString = magenta + cyan + green + blue
    

    finalString would show as

提交回复
热议问题