How do I make an attributed string using Swift? Ask Question

How do I make an attributed string using Swift? Ask Question

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

Where calculatedCoffee is an Int converted to a string and "attributedText" is the lowercase "g" with customized font that I am trying to create. Maybe I'm going about this the wrong way. Any help is appreciated!

ベストアンサー1

ここに画像の説明を入力してください

This answer has been updated for Swift 4.2.

Quick Reference

The general form for making and setting an attributed string is like this. You can find other common options below.

// create attributed string
let myString = "Swift Attributed String"
let myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.blue ]
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute) 

// set attributed text on a UILabel
myLabel.attributedText = myAttrString

テキストの色

let myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.blue ]

背景色

let myAttribute = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]

フォント

let myAttribute = [ NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 18.0)! ]

ここに画像の説明を入力してください

let myAttribute = [ NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue ]

ここに画像の説明を入力してください

let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width: 3, height: 3)
myShadow.shadowColor = UIColor.gray

let myAttribute = [ NSAttributedString.Key.shadow: myShadow ]

The rest of this post gives more detail for those who are interested.


Attributes

String attributes are just a dictionary in the form of [NSAttributedString.Key: Any], where NSAttributedString.Key is the key name of the attribute and Any is the value of some Type. The value could be a font, a color, an integer, or something else. There are many standard attributes in Swift that have already been predefined. For example:

  • key name: NSAttributedString.Key.font, value: a UIFont
  • key name: NSAttributedString.Key.foregroundColor, value: a UIColor
  • key name: NSAttributedString.Key.link, value: an NSURL or NSString

There are many others. See this link for more. You can even make your own custom attributes like:

  • key name: NSAttributedString.Key.myName, value: some Type.
    if you make an extension:

    extension NSAttributedString.Key {
        static let myName = NSAttributedString.Key(rawValue: "myCustomAttributeKey")
    }
    

Creating attributes in Swift

You can declare attributes just like declaring any other dictionary.

// single attributes declared one at a time
let singleAttribute1 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let singleAttribute2 = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
let singleAttribute3 = [ NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue ]

// multiple attributes declared at once
let multipleAttributes: [NSAttributedString.Key : Any] = [
    NSAttributedString.Key.foregroundColor: UIColor.green,
    NSAttributedString.Key.backgroundColor: UIColor.yellow,
    NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue ]

// custom attribute
let customAttribute = [ NSAttributedString.Key.myName: "Some value" ]

Note the rawValue that was needed for the underline style value.

Because attributes are just Dictionaries, you can also create them by making an empty Dictionary and then adding key-value pairs to it. If the value will contain multiple types, then you have to use Any as the type. Here is the multipleAttributes example from above, recreated in this fashion:

var multipleAttributes = [NSAttributedString.Key : Any]()
multipleAttributes[NSAttributedString.Key.foregroundColor] = UIColor.green
multipleAttributes[NSAttributedString.Key.backgroundColor] = UIColor.yellow
multipleAttributes[NSAttributedString.Key.underlineStyle] = NSUnderlineStyle.double.rawValue

Attributed Strings

属性を理解したので、属性付き文字列を作成できます。

初期化

属性付き文字列を作成するには、いくつかの方法があります。読み取り専用の文字列だけが必要な場合は、 を使用できますNSAttributedString。これを初期化する方法をいくつか示します。

// Initialize with a string only
let attrString1 = NSAttributedString(string: "Hello.")

// Initialize with a string and inline attribute(s)
let attrString2 = NSAttributedString(string: "Hello.", attributes: [NSAttributedString.Key.myName: "A value"])

// Initialize with a string and separately declared attribute(s)
let myAttributes1 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let attrString3 = NSAttributedString(string: "Hello.", attributes: myAttributes1)

後で属性や文字列の内容を変更する必要がある場合は、 を使用する必要がありますNSMutableAttributedString。宣言は非常に似ています。

// Create a blank attributed string
let mutableAttrString1 = NSMutableAttributedString()

// Initialize with a string only
let mutableAttrString2 = NSMutableAttributedString(string: "Hello.")

// Initialize with a string and inline attribute(s)
let mutableAttrString3 = NSMutableAttributedString(string: "Hello.", attributes: [NSAttributedString.Key.myName: "A value"])

// Initialize with a string and separately declared attribute(s)
let myAttributes2 = [ NSAttributedString.Key.foregroundColor: UIColor.green ]
let mutableAttrString4 = NSMutableAttributedString(string: "Hello.", attributes: myAttributes2)

属性付き文字列の変更

例として、この投稿の先頭にある属性付き文字列を作成しましょう。

まず、NSMutableAttributedString新しいフォント属性を持つを作成します。

let myAttribute = [ NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 18.0)! ]
let myString = NSMutableAttributedString(string: "Swift", attributes: myAttribute )

一緒に作業する場合は、次のように属性文字列をUITextView(またはUILabel) に設定します。

textView.attributedText = myString

使用しませtextView.text

結果は次のとおりです。

ここに画像の説明を入力してください

次に、属性が設定されていない別の属性付き文字列を追加します。(上でlet宣言したにもかかわらずmyString、 であるため、変更できることに注目NSMutableAttributedStringしてください。これは私にとってはむしろ Swift らしくないように思えますし、将来これが変更されたとしても驚かないでしょう。変更があった場合はコメントを残してください。)

let attrString = NSAttributedString(string: " Attributed Strings")
myString.append(attrString)

ここに画像の説明を入力してください

17次に、インデックス から始まり、長さ の「Strings」単語を選択します7。これは でありNSRange、Swift ではないことに注意してくださいRange。(この答え範囲の詳細については、を参照してください。) このaddAttributeメソッドを使用すると、最初の場所に属性キー名、2 番目の場所に属性値、3 番目の場所に範囲を配置できます。

var myRange = NSRange(location: 17, length: 7) // range starting at location 17 with a lenth of 7: "Strings"
myString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: myRange)

ここに画像の説明を入力してください

最後に、背景色を追加しましょう。変化をつけるために、addAttributesメソッドを使用しましょう ( に注意してくださいs)。このメソッドを使用すると、複数の属性を一度に追加できますが、ここでは 1 つだけ追加します。

myRange = NSRange(location: 3, length: 17)
let anotherAttribute = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
myString.addAttributes(anotherAttribute, range: myRange)

ここに画像の説明を入力してください

属性がいくつかの場所で重複していることに注意してください。属性を追加しても、既存の属性は上書きされません。

関連している

参考文献

おすすめ記事