cómo añadir Cadena de texto Atribuida con Cadena Atribuida en Swift


Quiero añadir un Texto Atribuido con otro Texto Atribuido en Swift. Proporcione cualquier código de ejemplo para la operación de adición de dos cadenas atribuidas en Swift.

Author: Sujith Thankachan, 2016-04-07

2 answers

Use NSMutableAttributedString

Pequeño ejemplo

let yourAttributes = [NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIFont.systemFontOfSize(15)]
let yourOtherAttributes = [NSForegroundColorAttributeName: UIColor.redColor(), NSFontAttributeName: UIFont.systemFontOfSize(25)]

let partOne = NSMutableAttributedString(string: "This is an example ", attributes: yourAttributes)
let partTwo = NSMutableAttributedString(string: "for the combination of Attributed String!", attributes: yourOtherAttributes)

let combination = NSMutableAttributedString()

combination.appendAttributedString(partOne)
combination.appendAttributedString(partTwo) 

Swift 3

let yourAttributes = [NSForegroundColorAttributeName: UIColor.black, NSFontAttributeName: UIFont.systemFont(ofSize: 15)]
let yourOtherAttributes = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont.systemFont(ofSize: 25)]

let partOne = NSMutableAttributedString(string: "This is an example ", attributes: yourAttributes)
let partTwo = NSMutableAttributedString(string: "for the combination of Attributed String!", attributes: yourOtherAttributes)

let combination = NSMutableAttributedString()

combination.append(partOne)
combination.append(partTwo)

combination representa su cadena final que contiene ambos formatos proporcionados por yourAttributes y yourOtherAttributes

 97
Author: glace,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-03 10:44:41

@respuesta de glace , modificada para evitar la declaración vacía NSMutableAttributedString. Válido en Swift 3.1:

let yourAttributes = [NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIFont.systemFontOfSize(15)]
let yourOtherAttributes = [NSForegroundColorAttributeName: UIColor.redColor(), NSFontAttributeName: UIFont.systemFontOfSize(25)]

let partOne = NSMutableAttributedString(string: "This is an example ", attributes: yourAttributes)
let partTwo = NSMutableAttributedString(string: "for the combination of Attributed String!", attributes: yourOtherAttributes)

partOne.append(part2)

partOne es entonces su cadena final con todos los atributos. No es necesario un "combinador" intermedio.

 9
Author: leanne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-14 14:55:26