2015-09-27 2 views
1

Если я получаю приписываемую строку из текстового поля с помощьюПолучить блоки текста из NSAttributedString

let text = input.attributedText! 
print(text) 

в Swift, то вывод состоит в следующем (когда вход содержит «привет» в регулярном тогда «мира» выделены жирным шрифтом)

hello { 
    NSColor = "UIDeviceWhiteColorSpace 0 1"; 
    NSFont = "<UICTFont: 0x134544930> font-family: \".SFUIText-Regular\"; font-weight: normal; font-style: normal; font-size: 17.00pt"; 
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 2, Tabs (\n 28L,\n 56L,\n 84L,\n 112L,\n 140L,\n 168L,\n 196L,\n 224L,\n 252L,\n 280L,\n 308L,\n 336L\n), DefaultTabInterval 0, Blocks (\n), Lists (\n), BaseWritingDirection 0, HyphenationFactor 0, TighteningForTruncation NO, HeaderLevel 0"; 
    NSShadow = "NSShadow {0, -1} color = {(null)}"; 
} 
    world{ 
    NSColor = "UIDeviceWhiteColorSpace 0 1"; 
    NSFont = "<UICTFont: 0x1345b12a0> font-family: \".SFUIText-Bold\"; font-weight: bold; font-style: normal; font-size: 17.00pt"; 
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 2, Tabs (\n 28L,\n 56L,\n 84L,\n 112L,\n 140L,\n 168L,\n 196L,\n 224L,\n 252L,\n 280L,\n 308L,\n 336L\n), DefaultTabInterval 0, Blocks (\n), Lists (\n), BaseWritingDirection 0, HyphenationFactor 0, TighteningForTruncation NO, HeaderLevel 0"; 
    NSShadow = "NSShadow {0, -1} color = {(null)}"; 
} 

Я могу видеть, что два блока по-разному отформатированный письменной форме представлены в двух блоках при печати на консоли. Теперь то, что я хочу сделать, - это цикл через все блоки и для каждого, получить текст и шрифт. Таким образом, в этом случае при первом запуске он найдет «Hello» и «font-family: \». SFUIText-Regular \ "; font-weight: normal; font-style: normal; font-size: 17.00pt "и второй раз было бы найти„мир“, и это шрифт

я могу перебрать шрифты, используя код

text.enumerateAttribute(NSFontAttributeName, inRange: NSMakeRange(0, text.length), options: NSAttributedStringEnumerationOptions()) { (font: AnyObject?, range: NSRange, usmp: UnsafeMutablePointer<ObjCBool>) -> Void in 

     print(font) 
    } 

есть ли способ сделать то же самое для самого текста?

ответ

1

Да - просто перечислите все атрибуты вместо одного.

Предполагая, что у вас есть приписываемое строку, как это:

// Create the string 

let text = NSMutableAttributedString(string: "hello world") 
let font = UIFont(name: ".SFUIText-Regular", size: 17)! 
let boldFont = UIFont(name: ".SFUIText-Bold", size: 17)! 

text.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor(), range: NSMakeRange(0, text.string.characters.count)) 

text.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, 6)) 
text.addAttribute(NSFontAttributeName, value: boldFont, range: NSMakeRange(6, 5)) 

Вы можете создать результат, похожий на тот, в вашем примере, как это:

// Enumerate the attributes 

text.enumerateAttributesInRange(NSMakeRange(0, text.string.characters.count), options: []) { (attribute, range, stop) -> Void in 
    let substring = (text.string as NSString).substringWithRange(range) 
    debugPrint(substring, attribute) 
} 

Выход выглядит следующим образом:

"hello " ["NSFont": <UICTFont: 0x7fba19724be0> font-family: ".SFUIText-Regular"; font-weight: normal; font-style: normal; font-size: 17.00pt, "NSColor": UIDeviceWhiteColorSpace 0 1] 
"world" ["NSFont": <UICTFont: 0x7fba1960d8d0> font-family: ".SFUIText-Bold"; font-weight: bold; font-style: normal; font-size: 17.00pt, "NSColor": UIDeviceWhiteColorSpace 0 1] 
+0

Спасибо, что работает. –

Смежные вопросы