Swift 3 NSAttributedString несколько атрибутов
только что началось быстро 3, и у меня проблемы с быстрым синтаксисом.
Я пытаюсь показать простой NSAttributedString
.
Итак, я установил свои атрибуты:
let attributeFontSaySomething : [String : AnyObject] = [NSFontAttributeName : UIFont.fontSaySomething()]
let attributeColorSaySomething : [String : AnyObject] = [NSForegroundColorAttributeName : UIColor.blue]
Затем я создаю свою строку:
let attStringSaySomething = NSAttributedString(string: "Say something", attributes: self.attributeFontSaySomething)
Что я хотел бы сделать, так это создать строку с моими 2 атрибутами не только один. Но когда я делаю:
let attStringSaySomething = NSAttributedString(string: "Say something", attributes: [self.attributeFontSaySomething, self.attributeColorSaySomething])
Xcode говорит мне, что я не могу и хочу, чтобы я изменил это для буквального словаря.
Как я могу создать свою строку с двумя атрибутами без использования NSMutableAttributedString
?
Ответы
Ответ 1
Основная проблема заключается в том, что вы передаете массив [attr.. , attr...]
, а не один словарь.
Вам нужно объединить два словаря в один
let attributeFontSaySomething : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 12.0)]
let attributeColorSaySomething : [String : Any] = [NSForegroundColorAttributeName : UIColor.blue]
var attributes = attributeFontSaySomething
for (key, value) in attributeColorSaySomething {
attributes(value, forKey: key)
}
let attStringSaySomething = NSAttributedString(string: "Say something", attributes: attributes)
Однако было бы проще создать словарь буквально:
let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 12.0), NSForegroundColorAttributeName : UIColor.blue]
Ответ 2
Просто создайте один словарь с двумя наборами атрибутов:
let attributes: [String:AnyObject] =
[NSFontAttributeName : UIFont.fontSaySomething(),
NSForegroundColorAttributeName : UIColor.blue]
И затем используйте словарь с парами ключ/значение при создании вашей атрибутной строки.
В Swift нет встроенного механизма для комбинирования словарей, но вы можете добавить переопределение оператора +
, если хотите добавить словари вместе (вам нужно будет решить, что делать, если оба словари содержали один и тот же ключ.)
Ответ 3
Спасибо за ответ @vadian
Обновление для Swift 4
let attributes : [NSAttributedStringKey : Any] = [NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue) : UIFont.systemFont(ofSize: 12.0), NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue) : UIColor(hex:"4C0000")]
refreshControl.attributedTitle=NSAttributedString(string: "Refreshing...", attributes: attributes)
Ответ 4
Используйте это:
let attStringSaySomething = NSAttributedString.init(string: "Hello", attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16), NSForegroundColorAttributeName:UIColor.black])
Ответ 5
Проблема заключается в том, что вы вставляете два словаря в словарь, что только ожидает [String: Any]
, а не [[String: Any], [String: Any]]
.
Вы можете сделать следующее:
let attStringSaySomething = NSAttributedString(string: "Say something", attributes: [NSFontAttributeName : UIFont.fontSaySomething(), NSForegroundColorAttributeName : UIColor.blue])
Вы также можете группировать значения в кортежи вместо словарей и вставлять их в словарь на основе ключа и значения:
let attributeFontSaySomething = (key: NSFontAttributeName, value: UIFont.fontSaySomething())
let attributeColorSaySomething = (key: NSForegroundColorAttributeName, value: UIColor.blue)
let attStringSaySomething = NSAttributedString(string: "Say something", attributes: [attributeFontSaySomething.key : attributeFontSaySomething.value,attributeColorSaySomething.key : attributeColorSaySomething.value])
Ответ 6
Вы можете использовать этот код для разных атрибутов для разных строк. С шрифтом Roboto (для шрифта Roboto используйте MDFRobotoFontLoader
)
let yourAttributes = [NSForegroundColorAttributeName: UIColor.black, NSFontAttributeName: MDFRobotoFontLoader.sharedInstance().regularFont(ofSize: 20)]
let finalString = NSMutableAttributedString(string: "", attributes: yourAttributes)
let attributeStr = NSMutableAttributedString(string: "XYZGFDGii", attributes: yourAttributes)
finalString.append(attributeStr)
let yourOtherAttributes = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: MDFRobotoFontLoader.sharedInstance().regularFont(ofSize: 24)]
let partTwo = NSMutableAttributedString(string: "hfjghlkdhkjld", attributes: yourOtherAttributes)
finalString.append(partTwo)
В этом примере используется шрифт Roboto