Rendre le text gras en utilisant la string atsortingbuée dans swift

J'ai une string comme celle-ci

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

Maintenant, remplacez text1 par une autre string, disons t 1 . Je suis capable de replace le text, mais je ne suis pas capable de le mettre en gras. Je veux mettre en gras la nouvelle string t 1 , de sorte que la sortie finale sera:

@t 1 c'est bon @t 1

Comment puis-je le faire?

Tous les exemples que je vois sont en Objective-C, mais je veux le faire dans Swift.

Merci d'avance.

Voici une manière soignée de faire une combinaison de texts gras et normaux dans une seule label.

Extension:

Swift 3.0

 extension NSMutableAtsortingbutedSsortingng { @discardableResult func bold(_ text:Ssortingng) -> NSMutableAtsortingbutedSsortingng { let attrs:[Ssortingng:AnyObject] = [NSFontAtsortingbuteName: UIFont(name: "AvenirNext-Medium", size: 12)!] let boldSsortingng = NSMutableAtsortingbutedSsortingng(ssortingng: text, atsortingbutes:attrs) self.append(boldSsortingng) return self } @discardableResult func normal(_ text:Ssortingng)->NSMutableAtsortingbutedSsortingng { let normal = NSAtsortingbutedSsortingng(ssortingng: text) self.append(normal) return self } } 

Swift 4

 extension NSMutableAtsortingbutedSsortingng { @discardableResult func bold(_ text: Ssortingng) -> NSMutableAtsortingbutedSsortingng { let attrs: [NSAtsortingbutedSsortingngKey: Any] = [.font: UIFont(name: "AvenirNext-Medium", size: 12)!] let boldSsortingng = NSMutableAtsortingbutedSsortingng(ssortingng:text, atsortingbutes: attrs) append(boldSsortingng) return self } @discardableResult func normal(_ text: Ssortingng) -> NSMutableAtsortingbutedSsortingng { let normal = NSAtsortingbutedSsortingng(ssortingng: text) append(normal) return self } } 

Usage:

 let formattedSsortingng = NSMutableAtsortingbutedSsortingng() formattedSsortingng .bold("Bold Text") .normal(" Normal Text ") .bold("Bold Text") let lbl = UILabel() lbl.atsortingbutedText = formattedSsortingng 

Résultat:

Texte en gras Texte normal Texte en gras

 var normalText = "Hi am normal" var boldText = "And I am BOLD!" var atsortingbutedSsortingng = NSMutableAtsortingbutedSsortingng(ssortingng:normalText) var attrs = [NSFontAtsortingbuteName : UIFont.boldSystemFont(ofSize: 15)] var boldSsortingng = NSMutableAtsortingbutedSsortingng(ssortingng:boldText, atsortingbutes:attrs) atsortingbutedSsortingng.appendAtsortingbutedSsortingng(boldSsortingng) 

Lorsque vous voulez l'atsortingbuer à une label:

 yourLabel.atsortingbutedText = atsortingbutedSsortingng 

modifier / mettre à jour: Xcode 8.3.2 • Swift 3.1

Si vous connaissez HTML et CSS, vous pouvez l'utiliser pour contrôler facilement le style de police, la couleur et la taille de votre string atsortingbuée comme suit:

 extension Ssortingng { var html2AttStr: NSAtsortingbutedSsortingng? { return try? NSAtsortingbutedSsortingng(data: Data(utf8), options: [NSDocumentTypeDocumentAtsortingbute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAtsortingbute: Ssortingng.Encoding.utf8.rawValue], documentAtsortingbutes: 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 

C'est le meilleur moyen que j'ai trouvé. Ajoutez une fonction que vous pouvez appeler de n'importe où et ajoutez-la à un file sans class comme Constants.swift, puis vous pouvez enhardir des mots à l'intérieur de n'importe quelle string, à de nombreuses occasions en appelant juste UNE LIGNE de code:

Pour aller dans un file constants.swift:

 import Foundation import UIKit func addBoldText(fullSsortingng: NSSsortingng, boldPartOfSsortingng: NSSsortingng, font: UIFont!, boldFont: UIFont!) -> NSAtsortingbutedSsortingng { let nonBoldFontAtsortingbute = [NSFontAtsortingbuteName:font!] let boldFontAtsortingbute = [NSFontAtsortingbuteName:boldFont!] let boldSsortingng = NSMutableAtsortingbutedSsortingng(ssortingng: fullSsortingng as Ssortingng, atsortingbutes:nonBoldFontAtsortingbute) boldSsortingng.addAtsortingbutes(boldFontAtsortingbute, range: fullSsortingng.rangeOfSsortingng(boldPartOfSsortingng as Ssortingng)) return boldSsortingng } 

Ensuite, vous pouvez simplement appeler cette ligne de code pour n'importe quel UILabel:

 self.UILabel.atsortingbutedText = addBoldText("Check again in 30 DAYS to find more friends", boldPartOfSsortingng: "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) 

Si vous travaillez avec des strings localisées, vous risquez de ne pas pouvoir countr sur la string en gras toujours à la fin de la phrase. Si tel est le cas, ce qui suit fonctionne bien:

par exemple, la requête "blah" ne correspond à aucun élément

 /* Create the search query part of the text, eg "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 ssortingng. Cast to NSSsortingng as we want range to be of type NSRange, not Swift's Range<Index> */ let range = (message as NSSsortingng).rangeOfSsortingng(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 atsortingbutedSsortingng = NSMutableAtsortingbutedSsortingng(ssortingng: message) atsortingbutedSsortingng.addAtsortingbute(NSFontAtsortingbuteName, value: UIFont.boldSystemFontOfSize(label.font.pointSize), range: range) /* Put the text in a label */ label.atsortingbutedText = atsortingbutedSsortingng 

J'ai étendu la grande réponse de David West pour que vous puissiez entrer une string et lui dire toutes les sous-strings que vous voudriez encourager:

 func addBoldText(fullSsortingng: NSSsortingng, boldPartsOfSsortingng: Array<NSSsortingng>, font: UIFont!, boldFont: UIFont!) -> NSAtsortingbutedSsortingng { let nonBoldFontAtsortingbute = [NSFontAtsortingbuteName:font!] let boldFontAtsortingbute = [NSFontAtsortingbuteName:boldFont!] let boldSsortingng = NSMutableAtsortingbutedSsortingng(ssortingng: fullSsortingng as Ssortingng, atsortingbutes:nonBoldFontAtsortingbute) for i in 0 ..< boldPartsOfSsortingng.count { boldSsortingng.addAtsortingbutes(boldFontAtsortingbute, range: fullSsortingng.rangeOfSsortingng(boldPartsOfSsortingng[i] as Ssortingng)) } return boldSsortingng } 

Et puis appelez comme ça:

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

Cela encouragera toutes les sous-strings que vous voulez mettre en gras dans votre string donnée

Cela pourrait être utile

 class func createAtsortingbutedSsortingngFrom (ssortingng1 : Ssortingng ,ssortingn2 : Ssortingng, atsortingbutes1 : Dictionary<Ssortingng, NSObject>, atsortingbutes2 : Dictionary<Ssortingng, NSObject>) -> NSAtsortingbutedSsortingng{ let fullSsortingngNormal = (ssortingng1 + ssortingn2) as NSSsortingng let atsortingbutedFullSsortingng = NSMutableAtsortingbutedSsortingng(ssortingng: fullSsortingngNormal as Ssortingng) atsortingbutedFullSsortingng.addAtsortingbutes(atsortingbutes1, range: fullSsortingngNormal.rangeOfSsortingng(ssortingng1)) atsortingbutedFullSsortingng.addAtsortingbutes(atsortingbutes2, range: fullSsortingngNormal.rangeOfSsortingng(ssortingn2)) return atsortingbutedFullSsortingng } 

S'appuyant sur les excellentes réponses de Jeremy Bader et David West, une extension Swift 3:

 extension Ssortingng { func withBoldText(boldPartsOfSsortingng: Array<NSSsortingng>, font: UIFont!, boldFont: UIFont!) -> NSAtsortingbutedSsortingng { let nonBoldFontAtsortingbute = [NSFontAtsortingbuteName:font!] let boldFontAtsortingbute = [NSFontAtsortingbuteName:boldFont!] let boldSsortingng = NSMutableAtsortingbutedSsortingng(ssortingng: self as Ssortingng, atsortingbutes:nonBoldFontAtsortingbute) for i in 0 ..< boldPartsOfSsortingng.count { boldSsortingng.addAtsortingbutes(boldFontAtsortingbute, range: (self as NSSsortingng).range(of: boldPartsOfSsortingng[i] as Ssortingng)) } return boldSsortingng } } 

Usage:

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

Swift 3.0

Convertissez html en string et changez la police selon votre condition.

 do { let str = try NSAtsortingbutedSsortingng(data: ("I'm a normal text and <b>this is my bold part . </b>And I'm again in the normal text".data(using: Ssortingng.Encoding.unicode, allowLossyConversion: true)!), options: [ NSDocumentTypeDocumentAtsortingbute: NSHTMLTextDocumentType], documentAtsortingbutes: nil) myLabel.atsortingbutedText = 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)! } 

Amélioration sur Prajeet Shrestha réponse: –

Vous pouvez créer une extension générique pour NSMutableAtsortingbutedSsortingng qui implique less de code. Dans ce cas, j'ai choisi d'utiliser la police système, mais vous pouvez l'adapter pour pouvoir entrer le nom de la police en tant que paramètre.

  extension NSMutableAtsortingbutedSsortingng { func systemFontWith(text: Ssortingng, size: CGFloat, weight: CGFloat) -> NSMutableAtsortingbutedSsortingng { let atsortingbutes: [Ssortingng: AnyObject] = [NSFontAtsortingbuteName: UIFont.systemFont(ofSize: size, weight: weight)] let ssortingng = NSMutableAtsortingbutedSsortingng(ssortingng: text, atsortingbutes: atsortingbutes) self.append(ssortingng) return self } }