
Ta odpowiedź została zaktualizowana do wersji Swift 4.2.
Krótki przegląd
Ogólna forma tworzenia i ustawiania przypisanego ciągu znaków jest następująca. Poniżej znajdziesz inne popularne opcje.
// 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 ]
Pozostała część tego postu zawiera więcej szczegółów dla zainteresowanych.
Atrybuty
Atrybuty ciągów to tylko słownik w formie [NSAttributedString.Key: Any], gdzie NSAttributedString.Keyjest kluczową nazwą atrybutu i Anywartością jakiegoś typu. Wartością może być czcionka, kolor, liczba całkowita lub coś innego. W Swift istnieje wiele standardowych atrybutów, które zostały wcześniej zdefiniowane. Na przykład:
- nazwa klucza:,
NSAttributedString.Key.fontwartość: aUIFont
- nazwa klucza:,
NSAttributedString.Key.foregroundColorwartość: aUIColor
- nazwa klucza:,
NSAttributedString.Key.linkwartość: an NSURLlubNSString
Jest wiele innych. Zobacz ten link, aby uzyskać więcej. Możesz nawet tworzyć własne atrybuty, takie jak:
nazwa klucza:, NSAttributedString.Key.myNamewartość: niektóre Wpisz.
jeśli zrobisz rozszerzenie :
extension NSAttributedString.Key {
static let myName = NSAttributedString.Key(rawValue: "myCustomAttributeKey")
}
Tworzenie atrybutów w Swift
Możesz zadeklarować atrybuty, tak jak zadeklarowanie innego słownika.
// 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" ]
Zwróć uwagę, rawValueże było to konieczne dla wartości stylu podkreślenia.
Ponieważ atrybuty są tylko Słownikami, możesz je również utworzyć, tworząc pusty Słownik, a następnie dodając do niego pary klucz-wartość. Jeśli wartość będzie zawierać wiele typów, musisz użyć jej Anyjako typu. Oto multipleAttributesprzykład z góry, odtworzony w ten sposób:
var multipleAttributes = [NSAttributedString.Key : Any]()
multipleAttributes[NSAttributedString.Key.foregroundColor] = UIColor.green
multipleAttributes[NSAttributedString.Key.backgroundColor] = UIColor.yellow
multipleAttributes[NSAttributedString.Key.underlineStyle] = NSUnderlineStyle.double.rawValue
Przypisane ciągi
Teraz, gdy rozumiesz atrybuty, możesz tworzyć przypisane ciągi.
Inicjalizacja
Istnieje kilka sposobów tworzenia przypisywanych ciągów. Jeśli potrzebujesz tylko ciągu tylko do odczytu, możesz go użyć NSAttributedString. Oto kilka sposobów na jego zainicjowanie:
// 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)
Jeśli będziesz musiał później zmienić atrybuty lub treść ciągu, powinieneś użyć NSMutableAttributedString. Deklaracje są bardzo podobne:
// 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)
Zmiana przypisanego ciągu
Jako przykład, stwórzmy przypisany ciąg na górze tego postu.
Najpierw utwórz NSMutableAttributedStringnowy atrybut czcionki.
let myAttribute = [ NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 18.0)! ]
let myString = NSMutableAttributedString(string: "Swift", attributes: myAttribute )
Jeśli pracujesz dalej, ustaw przypisany ciąg na UITextView(lub UILabel) w następujący sposób:
textView.attributedText = myString
Państwo nie używaćtextView.text .
Oto wynik:

Następnie dołącz kolejny przypisany ciąg, który nie ma żadnych ustawionych atrybutów. (Zauważ, że chociaż wcześniej letdeklarowałem myString, nadal mogę go modyfikować, ponieważ jest to NSMutableAttributedString. Wydaje mi się to dość szybkie i nie zdziwiłbym się, gdyby to się zmieniło w przyszłości. Zostaw mi komentarz, kiedy to nastąpi.)
let attrString = NSAttributedString(string: " Attributed Strings")
myString.append(attrString)

Następnie wybierzemy słowo „Ciągi”, które zaczyna się od indeksu 17i ma długość 7. Zauważ, że jest to NSRangeszybki, a nie szybki Range. (Zobacz tę odpowiedź, aby uzyskać więcej informacji na temat zakresów.) Ta addAttributemetoda pozwala nam umieścić nazwę klucza atrybutu w pierwszym miejscu, wartość atrybutu w drugim miejscu, a zakres w trzecim miejscu.
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)

Na koniec dodajmy kolor tła. Dla urozmaicenia zastosujmy addAttributesmetodę (zwróć uwagę na s). Mógłbym dodać wiele atrybutów jednocześnie za pomocą tej metody, ale dodam tylko jeden ponownie.
myRange = NSRange(location: 3, length: 17)
let anotherAttribute = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
myString.addAttributes(anotherAttribute, range: myRange)

Zauważ, że atrybuty nakładają się w niektórych miejscach. Dodanie atrybutu nie zastępuje już istniejącego atrybutu.
Związane z
Dalsza lektura
NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue | NSUnderlineStyle.PatternDot.rawValue