ios - nsattributedstringkey
¿Agregar NSUnderlineStyle.PatternDash a NSAttributedString en Swift? (4)
Estoy tratando de agregar un subrayado a un texto en mi aplicación Swift. Este es el código que tengo actualmente:
let text = NSMutableAttributedString(string: self.currentHome.name)
let attrs = [NSUnderlineStyleAttributeName:NSUnderlineStyle.PatternDash]
text.addAttributes(attrs, range: NSMakeRange(0, text.length))
homeLabel.attributedText = text
Pero recibo este error en la línea text.addAttributes :
NSStringno es idéntico aNSObject
¿Cómo puedo agregar un atributo contenido en una enumeración a un NSMutableAttributedString en Swift?
Actualización para la sintaxis de Swift 4 :
Aquí hay un ejemplo completo de UILabel crear una UILabel con texto subrayado:
let homeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
let text = NSMutableAttributedString(string: "hello, world!")
let attrs = [NSAttributedStringKey.underlineStyle: NSUnderlineStyle.patternDash.rawValue | NSUnderlineStyle.styleSingle.rawValue]
text.addAttributes(attrs, range: NSRange(location: 0, length: text.length))
homeLabel.attributedText = text
Swift 2:
Swift le permite pasar un Int a un método que toma un NSNumber , por lo que puede hacer esto un poco más limpio eliminando la conversión a NSNumber :
text.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: NSMakeRange(0, text.length))
Nota: esta respuesta se usó anteriormente toRaw() como se usó en la pregunta original, pero ahora es incorrecta porque toRaw() ha sido reemplazado por la propiedad rawValue partir de Xcode 6.1.
En Xcode 6.1, SDK iOS 8.1 toRaw() ha sido reemplazado por rawValue :
text.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: NSMakeRange(0, text.length))
O más fácil:
var text : NSAttributedString = NSMutableAttributedString(string: str, attributes : [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
Resulta que necesitaba el método toRaw() - esto funciona:
text.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(integer:(NSUnderlineStyle.StyleDouble).toRaw()), range: NSMakeRange(0, text.length))
Si desea una línea discontinua real, debe O | los valores sin procesar de las enumeraciones de PatternDash y StyleSingle como a continuación:
let dashed = NSUnderlineStyle.PatternDash.rawValue | NSUnderlineStyle.StyleSingle.rawValue
let attribs = [NSUnderlineStyleAttributeName : dashed, NSUnderlineColorAttributeName : UIColor.whiteColor()];
let attrString = NSAttributedString(string: plainText, attributes: attribs)