2016-11-24 2 views
11

только что начал быстро 3, и у меня проблемы с быстрым синтаксисом.Swift 3 NSAttributedString несколько атрибутов

Я пытаюсь отобразить простой 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 говорит мне, что я не могу и хочу, чтобы я изменил это для буквального словаря.

Как создать строку с атрибутами 2 без использования NSMutableAttributedString?

+0

имеет атрибуты должны быть обернуты в переменные? – dirtydanee

+0

Нет, нет, просто для более ясного. – user2206906

ответ

18

Основная проблема заключается в том, что вы пропускании массив[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] 
+0

Спасибо, человек. Я ценю. – user2206906

0

Использование так:

let attStringSaySomething = NSAttributedString.init(string: "Hello", attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16), NSForegroundColorAttributeName:UIColor.black]) 
5

Просто создать единый словарь с обоими наборами атрибутов:

let attributes: [String:AnyObject] = 
    [NSFontAttributeName : UIFont.fontSaySomething(), 
    NSForegroundColorAttributeName : UIColor.blue] 

И затем использовать словарь с обеих пар ключ/значение при создании приписываемое строки.

В Swift нет встроенного механизма для объединения словарей, но вы можете добавить переопределение оператора +, если хотите добавить словари вместе (вам нужно будет решить, что делать, если оба словаря содержали один и тот же ключ, однако.)

+0

Могу я попросить проверить версию Swift 4.0? Сначала я попытался создать массив [NSAttributedStringKey: AnyObject], но я не могу использовать NSAttribute ... Name. – Drwalcore

0

Проблема заключается в том, что вы вставляете два словаря в словарь , что только ожидает [String: Any], нет [[String: Any], [String: Any]] type. Вы можете сделать следующее:

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]) 
+0

Спасибо, человек, я думаю, что ответ правильный. – user2206906

+0

О, это сбой при использовании AsyncDisplayKit – user2206906

0

Вы можете использовать этот код для различных атрибутов на разных строках С 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 шрифт

1

Спасибо за ответ @ 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)