NSAttributedString é uma classe do framework Foundation no SDK iOS que representa uma string com um conjunto de atributos de formatação aplicados a caracteres individuais ou intervalos de texto. Ao contrário de NSString comum, NSAttributedString armazena não apenas caracteres Unicode, mas também um dicionário de atributos (fonte, cor, kerning, alinhamento) para cada segmento da string. De acordo com a Documentação do Desenvolvedor Apple (2026), NSAttributedString é a base para exibir texto formatado em todos os componentes de UI do iOS.
Pontos principais
NSAttributedString é uma classe fundamental do iOS/macOS para trabalhar com texto formatado. Ela estende NSString adicionando atributos à string — um dicionário de pares chave-valor onde a chave é uma constante NSAttributedStringKey (por exemplo, .font, .foregroundColor) e o valor é o objeto correspondente (UIFont, UIColor). Cada caractere na string pode ter seu próprio conjunto de atributos, permitindo formatação mista dentro de uma única string.
A arquitetura do NSAttributedString é baseada no conceito de execuções de atributos (attribute runs). Se você definir o atributo .font como UIFont.boldSystemFont(ofSize: 16) para o intervalo de caracteres 0..5, todos os caracteres desse intervalo aparecerão em negrito. Outros caracteres podem ter uma fonte diferente ou nenhum atributo. Ao renderizar uma string com atributos, o sistema UIKit mescla as características de diferentes intervalos e renderiza o texto uniformemente.
NSAttributedString é imutável — após a criação, seus atributos e conteúdo não podem ser alterados. Para modificação, existe a subclasse NSMutableAttributedString, que fornece métodos para adicionar, remover e alterar atributos em qualquer intervalo. Essa distinção é importante para multithreading: o NSAttributedString imutável é thread-safe, enquanto NSMutableAttributedString não é.
NSAttributedString suporta cerca de 40 atributos padrão definidos em NSAttributedStringKey. Cada atributo afeta um aspecto específico da aparência do texto: fonte, cor, posição, sublinhado, sombra, kerning, estilo de parágrafo e hiperlinks. Para definir um atributo, você usa uma constante NSAttributedStringKey e atribui a ela um objeto do tipo correspondente.
| Chave do atributo | Tipo do valor | Finalidade |
|---|---|---|
| .font | UIFont | Fonte e tamanho do texto |
| .foregroundColor | UIColor | Cor do texto |
| .backgroundColor | UIColor | Cor de fundo atrás do texto |
| .paragraphStyle | NSParagraphStyle | Alinhamento, espaçamento entre linhas, recuos |
| .kern | NSNumber (Float) | Espaçamento entre caracteres (kerning) |
| .underlineStyle | NSUnderlineStyle (Int) | Estilo de sublinhado (simples, duplo, grosso, padrão) |
| .strikethroughStyle | NSUnderlineStyle (Int) | Estilo de tachado |
| .link | NSURL | URL para hiperlink interativo |
| .shadow | NSShadow | Sombra do texto com offset, blurRadius e cor |
| .baselineOffset | NSNumber (Float) | Deslocamento do texto em relação à linha de base |
NSMutableParagraphStyle é um objeto que gerencia as características visuais de um parágrafo: alinhamento (.alignment: .left, .center, .right, .justified), espaçamento entre linhas (.lineSpacing), espaçamento entre parágrafos (.paragraphSpacing), recuo da primeira linha (.firstLineHeadIndent), recuo esquerdo e direito (.headIndent, .tailIndent) e direção do texto (.baseWritingDirection). ParagraphStyle é aplicado a um intervalo que inclui caracteres de nova linha se a mesma formatação for necessária para todo o parágrafo.
A criação de um NSAttributedString é feita através de um inicializador que recebe uma string e um dicionário de atributos. Os atributos são aplicados a toda a string. Para formatação mista (atributos diferentes em partes diferentes da string), usa-se NSMutableAttributedString com a adição posterior de atributos a intervalos específicos. Objective-C usa um dicionário NSAttributedStringKey: UIFont, enquanto Swift usa um dicionário [NSAttributedString.Key: Any] com segurança de tipos.
let plainText = "Hello, Swift!"
// Create with uniform attributes for the entire string
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.font:
UIFont.systemFont(ofSize: 18),
NSAttributedString.Key.foregroundColor:
UIColor.darkText,
NSAttributedString.Key.kern: 1.5
]
let attributedString =
NSAttributedString(string: plainText,
attributes: attributes)
Um exemplo demonstra a formatação de parágrafo via NSMutableParagraphStyle. Define-se alinhamento centralizado, espaçamento entre linhas de 8 pontos, espaçamento após parágrafo de 12 pontos. ParagraphStyle é adicionado ao dicionário de atributos sob a chave .paragraphStyle. NSAttributedString copia o paragraphStyle passado, portanto, após criar a string, você pode modificá-lo sem afetar a string já criada.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.center
paragraphStyle.lineSpacing = 8.0
paragraphStyle.paragraphSpacing = 12.0
paragraphStyle.firstLineHeadIndent = 20.0
let attributed = NSAttributedString(
string: "Centered paragraph with spacing",
attributes: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
NSMutableAttributedString é uma subclasse de NSAttributedString que permite modificar conteúdo e atributos após a criação. Métodos principais: addAttribute(_:value:range:) para adicionar um único atributo a um intervalo; addAttributes(_:range:) para adicionar vários atributos; setAttributes(_:range:) para substituir todos os atributos em um intervalo; removeAttribute(_:range:) para remover um atributo; replaceCharacters(in:with:) para substituir texto.
addAttribute e addAttributes adicionam atributos aos existentes sem remover os já definidos. Se um intervalo já tiver um atributo com a mesma chave, seu valor é substituído. setAttributes substitui completamente o dicionário de atributos para um intervalo — todos os atributos previamente definidos são removidos. Isso é importante ao formatar sequencialmente uma única string: addAttributes é mais seguro, pois não redefine fontes e cores já configuradas.
Os intervalos (NSRange) são especificados usando a estrutura NSRange(location: 0, length: 5). location é o índice inicial (baseado em 0), length é o número de caracteres. Se o intervalo exceder os limites da string, NSMutableAttributedString lança uma exceção NSRangeException. Para operações seguras com intervalos, use métodos NSRange do Foundation como NSIntersectionRange e NSUnionRange.
let attributed = NSMutableAttributedString(
string: "Bold and red text here")
// Apply bold font to first 9 characters
let boldRange = NSRange(location: 0, length: 9)
attributed.addAttribute(
NSAttributedString.Key.font,
value: UIFont.boldSystemFont(ofSize: 16),
range: boldRange)
// Apply red color to characters 13-16 ("text")
let redRange = NSRange(location: 13, length: 4)
attributed.addAttribute(
NSAttributedString.Key.foregroundColor,
value: UIColor.red,
range: redRange)
// Apply underline to the entire string
let fullRange = NSRange(location: 0,
length: attributed.length)
attributed.addAttribute(
NSAttributedString.Key.underlineStyle,
value: NSUnderlineStyle.single.rawValue,
range: fullRange)
A forma mais comum de exibir um NSAttributedString é atribuí-lo à propriedade attributedText de um UILabel. Diferente da propriedade text, attributedText usa os atributos para renderização, suportando formatação mista. Importante: se attributedText for definido, UILabel ignora as propriedades font, textColor e textAlignment — todas as características visuais vêm dos atributos do NSAttributedString.
let label = UILabel()
label.numberOfLines = 0
let fullText = NSMutableAttributedString(
string: "Price: $24.99 per month")
// Format "Price:" label with bold font
let priceLabelRange = NSRange(
location: 0, length: 6)
fullText.addAttribute(
NSAttributedString.Key.font,
value: UIFont.boldSystemFont(ofSize: 16),
range: priceLabelRange)
// Format "$24.99" with green color
let amountRange = NSRange(
location: 7, length: 6)
fullText.addAttribute(
NSAttributedString.Key.foregroundColor,
value: UIColor.systemGreen(),
range: amountRange)
fullText.addAttribute(
NSAttributedString.Key.font,
value: UIFont.boldSystemFont(ofSize: 22),
range: amountRange)
// Apply gray color to "per month" text
let periodRange = NSRange(
location: 14, length: 9)
fullText.addAttribute(
NSAttributedString.Key.foregroundColor,
value: UIColor.secondaryLabel,
range: periodRange)
label.attributedText = fullText
UITextView suporta links interativos em NSAttributedString. O atributo .link com um NSURL torna o texto clicável. Para lidar com toques, use o delegado UITextViewDelegate com o método textView(_:shouldInteractWith:in:interaction:). UITextView também suporta seleção de texto e uso de UIMenuController para operações padrão (copiar, pesquisar).
NSAttributedString suporta conversão de HTML e RTF via NSAttributedString.DocumentType. Para carregar HTML, use o inicializador com o parâmetro documentAttributes: NSAttributedString(data: htmlData, options: [.documentType: .html], documentAttributes: nil). Similarmente para RTF: .rtf ou .rtfd. Este mecanismo é útil para exibir conteúdo HTML sem WebView.
Para exportação para HTML, use o método data(from:documentAttributes:) com um intervalo e tipo de documento. Exportação HTML: try attributedString.data(from: fullRange, documentAttributes: [.documentType: .html]). Os dados resultantes podem ser salvos em um arquivo, enviados a um servidor ou exibidos em um WebView. Durante a exportação, fontes, cores, alinhamento, listas — todos os atributos de formatação — são convertidos em estilos CSS.
O suporte a RTF é especialmente relevante para aplicações macOS, onde RTF é o formato padrão de texto rico. iOS também suporta leitura e escrita de RTF, mas não o usa como formato principal. A diferença entre RTF e RTFD: RTFD inclui recursos incorporados (imagens) empacotados em um diretório. NSAttributedString pode manipular ambos os formatos através de uma única interface.
let htmlString = "<p><b>Bold<\/b> and <i>italic<\/i><\/p>"
guard let htmlData = htmlString.data(
using: String.Encoding.utf8) else { return }
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
NSAttributedString.DocumentReadingOptionKey.documentType:
NSAttributedString.DocumentType.html
]
let attributedFromHTML =
try? NSAttributedString(
data: htmlData,
options: options,
documentAttributes: nil)
Perguntas frequentes
NSString armazena apenas uma sequência de caracteres Unicode sem qualquer informação de formatação. NSAttributedString armazena caracteres e para cada subintervalo contém um dicionário de atributos (fonte, cor, estilo). Ao ser exibido, UIKit usa esses atributos para renderização, criando texto formatado.
A razão mais comum é usar a propriedade text em vez de attributedText. Ao atribuir via text, todos os atributos são ignorados. A segunda razão: após definir attributedText, você altera font, textColor ou textAlignment do UILabel — essas alterações redefinem attributedText. Use apenas attributedText para texto formatado.
Crie um NSMutableAttributedString e chame addAttribute(.font, value: boldFont, range: boldRange) para cada segmento com uma fonte diferente. Cada chamada aplica o atributo apenas ao intervalo especificado. Os caracteres restantes mantêm a fonte padrão ou outra definida anteriormente. Assim, criam-se execuções de atributos com fontes diferentes.
Sim, NSAttributedString lida corretamente com texto multilinha, incluindo caracteres de nova linha ( ). UITextView e UILabel (com numberOfLines = 0) quebram automaticamente o texto em uma nova linha. NSMutableParagraphStyle gerencia o espaçamento entre linhas, recuos e alinhamento para cada parágrafo independentemente.
Use NSMutableAttributedString com o atributo .foregroundColor para cada intervalo de cor. Para texto vermelho: addAttribute(.foregroundColor, value: UIColor.red, range: firstRange). Para azul: addAttribute(.foregroundColor, value: UIColor.blue, range: secondRange). As cores serão aplicadas apenas aos intervalos de caracteres especificados.
Resumo
Vamos desenvolver um aplicativo móvel chave na mão
A IT Sectr cria aplicativos para iOS e Android para startups e empresas desde 2017. Nós vamos aconselhá-lo e propor a melhor solução.
Leia também