2011-02-11 23 views
12

Estoy tratando de crear una cadena atribuida con un tachado, sin embargo, esta simple tarea parece ser más difícil de entender de lo que esperaba. Esto es lo que tengo actualmente (que no funciona). ¡Gracias por la ayuda!NSAttributedString con tachado

NSAttributedString *theTitle = [[[NSAttributedString alloc] initWithString:@"strikethrough text" attributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSColor whiteColor], NSForegroundColorAttributeName, NSUnderlinePatternSolid, NSStrikethroughStyleAttributeName, nil]] autorelease]; 

Respuesta

18

En primer lugar, el valor para NSStrikethroughStyleAttributeName debe ser un NSNumber, no un número entero simple. En segundo lugar, yo creo que hay que incluir NSUnderlineStyleSingle:

...:[NSDictionary dictionaryWithObjectsAndKeys: 
     ..., 
     [NSNumber numberWithInteger:NSUnderlinePatternSolid | NSUnderlineStyleSingle], 
     NSStrikethroughStyleAttributeName, 
     nil]... 
+0

Funcionó perfectamente ... gracias. – ambientdiscourse

+0

Esto fue muy útil. ¡Gracias! De nota, le falta un corchete de cierre para cerrar el mensaje 'numberWithInteger:' después de 'NSUnderlinePatternSolid | NSUnderlineStyleSingle' y antes ', NSStrikethroughStyleAttributeName'. – morgant

15

También puede simplemente usar:

NSAttributedString *theAttributedString; 
theAttributedString = [[NSAttributedString alloc] initWithString:theString 
      attributes:@{NSStrikethroughStyleAttributeName: 
      [NSNumber numberWithInteger:NSUnderlineStyleSingle]}]; 

Actualización:

Swift 2.0 versión

let theAttributedString = NSAttributedString(string: theString, attributes: [NSStrikethroughColorAttributeName: NSUnderlineStyle.StyleSingle]) 
+1

Esto es incorrecto, no puede asignar estilo al atributo de color. '[NSStrikethroughColorAttributeName: NSUnderlineStyle.StyleSingle]' –

2
func addAttributes(attrs: [String : AnyObject], range: NSRange) 

NSUnderlineStyleAttributeName: El valor de este atributo es un objeto NSNumber que contiene un número entero.

Desde rawValue la NSUnderlineStyle de enumeración es tipo int, debe inicializar un objeto NSNumber con él

Swift2.1:

attrStr.addAttributes([NSStrikethroughStyleAttributeName: NSNumber(integer: NSUnderlineStyle.StyleSingle.rawValue)], range: NSMakeRange(x, y)) 

x es la ubicación, el inicio de su texto

y es la longitud del texto

+0

El rango no funciona cuando escribo 'NSRangeMake (0, 4)' que no funciona, si escribo 'NSRangeMake (0, theAttributedString.lenght)' que funciona, pero mi Requisito para poner la línea horizontal en solo Primeros cuatro caracteres en Cadena, ¿cómo puedo hacer esto? – Dhiru

+0

Existe un error conocido en iOS 10.3 donde el atributo de paso no funcionará si se aplica en un rango. Como solución, puede hacer lo siguiente: 'attrStr.addAttributes ([NSBaselineOffsetAttributeName: NSNumber (integerLiteral: 0)], rango: NSMakeRange (x, y))' – jdev

Cuestiones relacionadas