Making text bold using attributed string in swift

bold text in swift
change font of attributed string swift
bold & non-bold text in a single uilabel
change font size of attributed string swift
append attributed string swift
nsattributedstring bold
make attributed string in swift
nsattributedstring add attribute

I have a string like this

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

Now replace text1 with another string, say t 1. I am able to replace the text, but i am not able to bold it. I want to bold the new string t 1, so that the final output will be:

@t 1 this is good @t 1

How can I do it?

All the examples I am seeing are in Objective-C, but I want to do it in Swift.

Thanks in advance.

Here is a neat way to make a combination of bold and normal texts in a single label.

Extension:

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
    }
}

Usage:

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

let lbl = UILabel()
lbl.attributedText = formattedString

Result:

Bold Text Normal Text Bold Text

NSAttributedString by example – Hacking with Swift, Swift's strings are plain text, which works fine in the vast majority of cases we But sometimes we want more – we want to be able to add formatting like bold or It's common to use an explicit type annotation when making attributed strings,  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.

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)

When you want to assign it to a label:

yourLabel.attributedText = attributedString

Formatting strings with NSAttributedString, How do I change the color of an attributed string in Swift? We will need a string and attributed text string. I’m using a NSMutableAttributedString so I can add attributes as we go along in the lesson. If you have only one time you set attributes, you can do that with a NSAttributedString. Initializing an Attributed String. in the viewDidLoad method, add the following code:

edit/update: Xcode 8.3.2 • Swift 3.1

If you know HTML and CSS you can use it to easily control the font style, color and size of your attributed string as follow:

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

How to use Bold & Non-Bold Text In A Single UILabel in iOS/iPhone?, is published by Shubham Gupta in Swift India. As sometimes writing code, we stuck at situation like, some bold & normal text at single phrase, Create multiple labels, assigning different font style & other property, alligning them together, A big NO. Intiate NSMutableAttributedString , with multiple style property & assign to  bold part of string in UITextView swift. Ask Question possible duplicate of Making text bold using attributed string in swift – Larme Jul 27 '15 at 7:55.

If you're working with localised strings, you might not be able to rely on the bold string always being at the end of the sentence. If this is the case then the following works well:

e.g. Query "blah" does not match any items

/* 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

Changing specific text's color using NSMutableAttributedString in Swift, Most of the time you can get by with just having one font style for a given label, text view, etc. But what if you're trying to make a single word within a string bold? Xcode 10. Swift 4.2. Basic knowledge of Strings and UILabels  Making a Mutable String. We will need an attributed text string. There are two varieties NSMutableAttributedString and AttributedString. If you are wondering why one has a NS in front and the other doesn’t so am I. Since I’m using Beta 1 of Xcode 8, Apple is still working on removing all the NS‘s they promised to remove. If your code doesn’t work because it can’t find something with an NS prefix, try removing the NS.

This is the best way that I have come up with. Add a function you can call from anywhere and add it to a file without a class like Constants.swift and then you can embolden words within any string, on numerous occasions by calling just ONE LINE of code:

To go in a constants.swift file:

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
}

Then you can just call this one line of code for any 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)

NSAttributedString, Here is a neat way to make a combination of bold and normal texts in a single label. Extension: Swift 3.0 extension NSMutableAttributedString { @  Attributed strings are strings with formatting attached, which means fonts, colors, alignment, line spacing and more. They are supported in many places around iOS, which means you can assign a fully formatted string to a UILabel and have it look great with no further work.

Attributed Strings iOS Tutorial, var normalText = "Hi am normal" var boldText = "And I am BOLD!" var attributedString = NSMutableAttributedString(string:normalText) var attrs  NSAttributedString by example. Swift's strings are great for storing plain text, but as soon as you want formatting, images, or interactivity you need to reach for NSAttributedString - Foundation’s all-in-one string handling class.

Multiple Font, Style for UILable Text using NSAttributed String., Extension: Swift 3.0 extension NSMutableAttributedString { #discardableResult func bold(_ text:String) -> NSMutableAttributedString { let attrs:[String:AnyObject]​  Use attributed string: // Define attributes let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18) let attributes :Dictionary = [NSFontAttributeName : labelFont] // Create attributed string var attrString = NSAttributedString(string: "Foo", attributes:attributes) label.attributedText = attrString You need to define attributes.

Using NSAttributedString for Multiple Font Styles in a Single Label , To use a Bold and a regular/Non-Bold text in a single UILabel, we can either use a viewDidLoad() let boldAttribute = [ NSAttributedString. You can make interactive hyperlinks in any attributed string, which in turn means you can add interactive hyperlinks to any UIKit control. If you're working with UITextView (which is likely, let's face it), you get basic hyperlinks just by enabling the "Links" data detector in Interface Builder, but that doesn't work for arbitrary strings – for example, maybe you want the words “tap here" to be interactive.

Comments
  • You need to decompose you issue: Learn how to "bold": stackoverflow.com/questions/25199580/… Learn how to replace text.
  • Use this library, it's petty simple. github.com/iOSTechHub/AttributedString
  • is it not for swift 2 ?
  • A small addition: func bold(_ text:String, _ size:CGFloat). I added size to the bold so I can control it from outside. Also, I missed the AvenirNext-Medium font in this function so took me few minutes to understand why I can't see my font. Heads up.
  • you saved my day, dude!
  • Thanks! Worked like charm :)
  • Ballay ballay sarkaaar :D
  • Awesome answer! Thanks!
  • note: appendAttributedString has been renamed to .append()
  • I am trying to implement this in Swift 2 Xcode, but the font is not being applied. Here is the String: <link href=\"https://fonts.googleapis.com/css?family=Frank+Ruhl+Libre\" rel=\"stylesheet\"> <span style=\"font-family: 'Frank Ruhl Libre', sans-serif;\">שלום</span>