trucos negrita letra escribir como colores ios swift ios8 nsmutableattributedstring

ios - letra - Poner el texto en negrita usando una cadena atribuida en Swift



markdown discord (17)

Tengo una cuerda como esta

var str = "@text1 this is good @text1"

Ahora reemplace text1 con otra cadena, digamos t 1 . Puedo reemplazar el texto, pero no puedo ponerlo en negrita. Quiero poner en negrita la nueva cadena t 1 , para que el resultado final sea:

@t 1 esto es bueno @t 1

¿Cómo puedo hacerlo?

Todos los ejemplos que estoy viendo están en Objective-C, pero quiero hacerlo en Swift.

Gracias por adelantado.


Swift 4 y superior

Para Swift 4 y superior, esa es una buena manera:

let attributsBold = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16, weight: .bold)] let attributsNormal = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16, weight: .regular)] var attributedString = NSMutableAttributedString(string: "Hi ", attributes:attributsNormal) let boldStringPart = NSMutableAttributedString(string: "John", attributes:attributsBold) attributedString.append(boldStringPart) yourLabel.attributedText = attributedString

En la etiqueta el texto se ve así: "Hola John "


Aceptando como válida la respuesta de en este hilo, me gustaría extender su solución usando la Etiqueta si se conoce y los rasgos de la fuente.

Swift 4

extension NSMutableAttributedString { @discardableResult func normal(_ text: String) -> NSMutableAttributedString { let normal = NSAttributedString(string: text) append(normal) return self } @discardableResult func bold(_ text: String, withLabel label: UILabel) -> NSMutableAttributedString { //generate the bold font var font: UIFont = UIFont(name: label.font.fontName , size: label.font.pointSize)! font = UIFont(descriptor: font.fontDescriptor.withSymbolicTraits(.traitBold) ?? font.fontDescriptor, size: font.pointSize) //generate attributes let attrs: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font] let boldString = NSMutableAttributedString(string:text, attributes: attrs) //append the attributed text append(boldString) return self } }


Aquí hay una forma ordenada de hacer una combinación de textos en negrita y normales en una sola etiqueta.

Extensión:

Swift 3.0

extension NSMutableAttributedString { @discardableResult func bold(_ text:String) -> NSMutableAttributedString { let attrs:[String:AnyObject] = [NSFontAttributeName: UIFont(name: "AvenirNext-Medium", size: 12)!] let boldString = NSMutableAttributedString(string: text, attributes:attrs) self.append(boldString) return self } @discardableResult func normal(_ text:String)->NSMutableAttributedString { let normal = NSAttributedString(string: text) self.append(normal) return self } }

Swift 4

extension NSMutableAttributedString { @discardableResult func bold(_ text: String) -> NSMutableAttributedString { let attrs: [NSAttributedStringKey: Any] = [.font: UIFont(name: "AvenirNext-Medium", size: 12)!] let boldString = NSMutableAttributedString(string:text, attributes: attrs) append(boldString) return self } @discardableResult func normal(_ text: String) -> NSMutableAttributedString { let normal = NSAttributedString(string: text) append(normal) return self } }

Uso:

let formattedString = NSMutableAttributedString() formattedString .bold("Bold Text") .normal(" Normal Text ") .bold("Bold Text") let lbl = UILabel() lbl.attributedText = formattedString

Resultado:

Texto en negrita Texto normal Texto en negrita


Esta es la mejor manera que se me ocurrió. Agregue una función a la que pueda llamar desde cualquier lugar y agréguela a un archivo sin una clase como Constants.swift y luego puede envalentonar palabras dentro de cualquier cadena, en numerosas ocasiones llamando solo UNA LÍNEA de código:

Para ir en un archivo constants.swift:

import Foundation import UIKit func addBoldText(fullString: NSString, boldPartOfString: NSString, font: UIFont!, boldFont: UIFont!) -> NSAttributedString { let nonBoldFontAttribute = [NSFontAttributeName:font!] let boldFontAttribute = [NSFontAttributeName:boldFont!] let boldString = NSMutableAttributedString(string: fullString as String, attributes:nonBoldFontAttribute) boldString.addAttributes(boldFontAttribute, range: fullString.rangeOfString(boldPartOfString as String)) return boldString }

Entonces puede llamar a esta línea de código para cualquier UILabel:

self.UILabel.attributedText = addBoldText("Check again in 30 DAYS to find more friends", boldPartOfString: "30 DAYS", font: normalFont!, boldFont: boldSearchFont!) //Mark: Albeit that you''ve had to define these somewhere: let normalFont = UIFont(name: "INSERT FONT NAME", size: 15) let boldFont = UIFont(name: "INSERT BOLD FONT", size: 15)


Esto podría ser útil.

class func createAttributedStringFrom (string1 : String ,strin2 : String, attributes1 : Dictionary<String, NSObject>, attributes2 : Dictionary<String, NSObject>) -> NSAttributedString{ let fullStringNormal = (string1 + strin2) as NSString let attributedFullString = NSMutableAttributedString(string: fullStringNormal as String) attributedFullString.addAttributes(attributes1, range: fullStringNormal.rangeOfString(string1)) attributedFullString.addAttributes(attributes2, range: fullStringNormal.rangeOfString(strin2)) return attributedFullString }


Extendí la excelente respuesta de David West para que pueda ingresar una cadena y decirle todas las subcadenas que desea envalentonar:

func addBoldText(fullString: NSString, boldPartsOfString: Array<NSString>, font: UIFont!, boldFont: UIFont!) -> NSAttributedString { let nonBoldFontAttribute = [NSFontAttributeName:font!] let boldFontAttribute = [NSFontAttributeName:boldFont!] let boldString = NSMutableAttributedString(string: fullString as String, attributes:nonBoldFontAttribute) for i in 0 ..< boldPartsOfString.count { boldString.addAttributes(boldFontAttribute, range: fullString.rangeOfString(boldPartsOfString[i] as String)) } return boldString }

Y luego llámalo así:

let normalFont = UIFont(name: "Dosis-Medium", size: 18) let boldSearchFont = UIFont(name: "Dosis-Bold", size: 18) self.UILabel.attributedText = addBoldText("Check again in 30 days to find more friends", boldPartsOfString: ["Check", "30 days", "find", "friends"], font: normalFont!, boldFont: boldSearchFont!)

Esto envalentonará todas las subcadenas que desee en negrita en su cadena dada


Mejorando la respuesta de Prajeet Shrestha: -

Puede hacer una extensión genérica para NSMutableAttributedString que implica menos código. En este caso, he elegido utilizar la fuente del sistema, pero puede adaptarla para poder ingresar el nombre de la fuente como parámetro.

extension NSMutableAttributedString { func systemFontWith(text: String, size: CGFloat, weight: CGFloat) -> NSMutableAttributedString { let attributes: [String: AnyObject] = [NSFontAttributeName: UIFont.systemFont(ofSize: size, weight: weight)] let string = NSMutableAttributedString(string: text, attributes: attributes) self.append(string) return self } }


Puede hacerlo utilizando un método personalizado simple escrito a continuación. Debe dar una cadena completa en el primer parámetro y el texto para que esté en negrita en el segundo parámetro. Espero que esto ayude.

func getAttributedBoldString(str : String, boldTxt : String) -> NSMutableAttributedString { let attrStr = NSMutableAttributedString.init(string: str) let boldedRange = NSRange(str.range(of: boldTxt)!, in: str) attrStr.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 17, weight: .bold)], range: boldedRange) return attrStr }

uso: initalString = Soy un niño

label.attributedText = getAttributedBoldString (str: initalString, boldTxt: "Boy")

cadena resultante = Soy un niño


Si está trabajando con cadenas localizadas, es posible que no pueda confiar en que la cadena en negrita siempre esté al final de la oración. Si este es el caso, entonces lo siguiente funciona bien:

por ejemplo, la consulta "bla" no coincide con ningún elemento

/* Create the search query part of the text, e.g. "blah". The variable ''text'' is just the value entered by the user. */ let searchQuery = "/"/(text)/"" /* Put the search text into the message */ let message = "Query /(searchQuery). does not match any items" /* Find the position of the search string. Cast to NSString as we want range to be of type NSRange, not Swift''s Range<Index> */ let range = (message as NSString).rangeOfString(searchQuery) /* Make the text at the given range bold. Rather than hard-coding a text size, Use the text size configured in Interface Builder. */ let attributedString = NSMutableAttributedString(string: message) attributedString.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(label.font.pointSize), range: range) /* Put the text in a label */ label.attributedText = attributedString


Sobre la base de las excelentes respuestas de Jeremy Bader y David West, una extensión de Swift 3:

extension String { func withBoldText(boldPartsOfString: Array<NSString>, font: UIFont!, boldFont: UIFont!) -> NSAttributedString { let nonBoldFontAttribute = [NSFontAttributeName:font!] let boldFontAttribute = [NSFontAttributeName:boldFont!] let boldString = NSMutableAttributedString(string: self as String, attributes:nonBoldFontAttribute) for i in 0 ..< boldPartsOfString.count { boldString.addAttributes(boldFontAttribute, range: (self as NSString).range(of: boldPartsOfString[i] as String)) } return boldString } }

Uso:

let label = UILabel() let font = UIFont(name: "AvenirNext-Italic", size: 24)! let boldFont = UIFont(name: "AvenirNext-BoldItalic", size: 24)! label.attributedText = "Make sure your face is/nbrightly and evenly lit".withBoldText( boldPartsOfString: ["brightly", "evenly"], font: font, boldFont: boldFont)


Solo usa código como este:

let font = UIFont(name: "Your-Font-Name", size: 10.0)! let attributedText = NSMutableAttributedString(attributedString: noteLabel.attributedText!) let boldedRange = NSRange(attributedText.string.range(of: "Note:")!, in: attributedText.string) attributedText.addAttributes([NSAttributedString.Key.font : font], range: boldedRange) noteLabel.attributedText = attributedText


Swift 3.0

Convierta html a cadena y cambio de fuente según su requisito.

do { let str = try NSAttributedString(data: ("I''m a normal text and <b>this is my bold part . </b>And I''m again in the normal text".data(using: String.Encoding.unicode, allowLossyConversion: true)!), options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) myLabel.attributedText = str myLabel.font = MONTSERRAT_BOLD(23) myLabel.textAlignment = NSTextAlignment.left } catch { print(error) }


func MONTSERRAT_BOLD(_ size: CGFloat) -> UIFont { return UIFont(name: "MONTSERRAT-BOLD", size: size)! }


Una forma súper fácil de hacer esto.

let text = "This string is having multiple font" let attributedText = NSMutableAttributedString.getAttributedString(fromString: text) attributedText.apply(font: UIFont.boldSystemFont(ofSize: 24), subString: "This") attributedText.apply(font: UIFont.boldSystemFont(ofSize: 24), onRange: NSMakeRange(5, 6))

Para obtener más detalles, haga clic aquí: github.com/iOSTechHub/AttributedString


dos trazador de líneas en swift 4:

extension NSMutableAttributedString { func systemFontWith(text: String, size: CGFloat, weight: CGFloat) -> NSMutableAttributedString { let attributes: [String: AnyObject] = [NSFontAttributeName: UIFont.systemFont(ofSize: size, weight: weight)] let string = NSMutableAttributedString(string: text, attributes: attributes) self.append(string) return self } }


editar / actualizar: Xcode 8.3.2 • Swift 3.1

Si conoce HTML y CSS, puede usarlo para controlar fácilmente el estilo de fuente, el color y el tamaño de su cadena atribuida de la siguiente manera:

extension String { var html2AttStr: NSAttributedString? { return try? NSAttributedString(data: Data(utf8), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil) } } "<style type=/"text/css/">#red{color:#F00}#green{color:#0F0}#blue{color: #00F; font-weight: Bold; font-size: 32}</style><span id=/"red/" >Red,</span><span id=/"green/" > Green </span><span id=/"blue/">and Blue</span>".html2AttStr


uso....

let attrString = NSMutableAttributedString() .appendWith(weight: .semibold, "almost bold") .appendWith(color: .white, weight: .bold, " white and bold") .appendWith(color: .black, ofSize: 18.0, " big black")

dos centavos...

extension NSMutableAttributedString { @discardableResult func appendWith(color: UIColor = UIColor.darkText, weight: UIFont.Weight = .regular, ofSize: CGFloat = 12.0, _ text: String) -> NSMutableAttributedString{ let attrText = NSAttributedString.makeWith(color: color, weight: weight, ofSize:ofSize, text) self.append(attrText) return self } } extension NSAttributedString { public static func makeWith(color: UIColor = UIColor.darkText, weight: UIFont.Weight = .regular, ofSize: CGFloat = 12.0, _ text: String) -> NSMutableAttributedString { let attrs = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: ofSize, weight: weight), NSAttributedStringKey.foregroundColor: color] return NSMutableAttributedString(string: text, attributes:attrs) } }


var normalText = "Hi am normal" var boldText = "And I am BOLD!" var attributedString = NSMutableAttributedString(string:normalText) var attrs = [NSFontAttributeName : UIFont.boldSystemFont(ofSize: 15)] var boldString = NSMutableAttributedString(string: boldText, attributes:attrs) attributedString.append(boldString)

Cuando desee asignarlo a una etiqueta:

yourLabel.attributedText = attributedString