Estaba planeando usar NSAttributedString para resaltar porciones de cadenas con la consulta correspondiente de la búsqueda de un usuario. Sin embargo, no puedo encontrar un equivalente de iOS de NSBackgroundColorAttributeName
; no hay kCTBackgroundColorAttributeName
. ¿Existe tal cosa, similar a la forma en que NSForegroundColorAttributeName
se convierte en kCTForegroundColorAttributeName
?NSBackgroundColorAttributeName-like atributo en NSAttributedString en iOS?
Respuesta
No, dicho atributo no existe en Core Text, deberá dibujar sus propios rectángulos debajo del texto para simularlo.
Básicamente, tendrá que averiguar qué rectángulo (s) rellenar para un rango determinado en la cadena. Si realiza su diseño con un CTFramesetter
que produce un CTFrame
, necesita obtener sus líneas y sus orígenes usando CTFrameGetLines
y CTFrameGetLineOrigins
.
Luego itere sobre las líneas y use CTLineGetStringRange
para averiguar qué líneas forman parte del rango que desea resaltar. Para obtener los rectángulos para llenar, use CTLineGetTypographicBounds
(para la altura) y CTLineGetOffsetForStringIndex
(para el desplazamiento horizontal y el ancho).
Gran respuesta. Es una pena que no haya un atributo simple para reemplazar todo ese código. – kevboh
Mi proyecto DTCoreText admite resaltar de la misma manera que funciona en Mac. Tiene un método NSAttributedString initWithHTMLData para obtener el formato HTML para la cadena atribuida y una clase de vista que muestra correctamente cadenas atribuidas con muchas características adicionales sobre CATextLayer. – Cocoanetics
NSBackgroundColorAttributeName está disponible en iOS 6, y se puede utilizar por la siguiente manera:
[_attributedText addAttribute: NSBackgroundColorAttributeName value:[UIColor yellowColor] range:textRange];
[_attributedText drawInRect:rect];
drawInRect:
apoyará NSBackgroundColorAttributeName y todas NS * attributeNames el apoyo de iOS 6.
Para CTFrameDraw() existe no es compatible con el color del texto de fondo.
Código:
- (void)drawRect:(CGRect)rect {
// First draw selection/marked text, then draw text
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
[_attributedText drawInRect:rect];
CGContextRestoreGState(context);
// CTFrameDraw(_frame, UIGraphicsGetCurrentContext());
}
¡Impresionante, gracias por la actualización! – kevboh
- 1. ¿Puedo usar NSAttributedString en Core Text en iOS?
- 2. Copia NSAttributedString en UIPasteBoard
- 3. Copie NSAttributedString en el cartón
- 4. ¿Cómo convierto NSAttributedString en cadena HTML?
- 5. Cambiar el color de fondo en NSAttributedString
- 6. ¿Cómo se muestra NSAttributedString en un iPhone?
- 7. Transformar un NSAttributedString en texto sin formato
- 8. Mostrar NSAttributedString usando CoreText
- 9. Cómo configurarHighlightedTextColor @ NSAttributedString
- 10. NSAttributedString con tachado
- 11. ¿Cómo se define un párrafo en un NSAttributedString?
- 12. cómo cambiar caracteres mayúsculas a superior en NSAttributedString
- 13. NSAttributedString kCTParagraphStyleSpecifierParagraphSpacing no tiene ningún efecto
- 14. ¿Cómo hacer subíndices y superíndices usando NSAttributedString?
- 15. Deshacer operación con NSUndoManager en rich UITextView (iOS 6)
- 16. atributo NUnit SetUpFixture atributo en xUnit?
- 17. Como llegar a la altura NSAttributedString a un ancho fijo
- 18. ¿Cómo se acaricia el _outside_ de un NSAttributedString?
- 19. Atributo inverso en NHibernate
- 20. atributo faltante en activerecord
- 21. UIHint Atributo en MVC
- 22. Agregar el atributo "No hacer copia de seguridad" a una jerarquía de carpetas en iOS 5.0.1
- 23. Obtener nombre de archivo y ruta desde nsfilewrapper/nstextattachment en NSAttributedString
- 24. ¿Por qué los hipervínculos a veces no se muestran en NSTextField con NSAttributedString?
- 25. DropDownListFor con un atributo personalizado con - en nombre de atributo?
- 26. Atributo personalizado escrito en C# ASP.Net MVC como Autorizar atributo
- 27. Alternar atributo deshabilitado en jquery
- 28. Obtener atributo href en jQuery
- 29. Atributo personalizado en UserControl (* .ascx)?
- 30. Apple SearchKit en iOS
ver si esto ayuda http://stackoverflow.com/questions/5424003/changing-background-color-on-nsattributedstring –
Gracias, por desgracia, ya NSAttributedString se presenta en CoreText Pongo No creo que haya puntos de vista para los que pueda cambiar el color de fondo. – kevboh
@kevboh He escrito un HighlightLabel (http://github.com/dineshrajas/HighlightLabel). Adelante, si aún lo necesitas. –