Making Text Bold Using Attributed String in Swift

bold part of string in UITextView swift

Updated for Swift 3

func attributedText() -> NSAttributedString {

let string = "TERMS OF SERVICE\nLast Updated: May 7, 2015\n\nPLEASE NOTE: The HIGO Terms of Service as stated below is effective as of the 'Last Updated' date above for any user who is browsing the HIGO website, or for any user who creates a HIGO account on or after that date." as NSString

let attributedString = NSMutableAttributedString(string: string as String, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 15.0)])

let boldFontAttribute = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 15.0)]

// Part of string to be bold
attributedString.addAttributes(boldFontAttribute, range: string.range(of: "TERMS OF SERVICE"))
attributedString.addAttributes(boldFontAttribute, range: string.range(of: "PLEASE NOTE:"))

// 4
return attributedString
}

And set attributext text to your text view as:

legalText.attributedText = attributedText()

Making part of localised string bold swift

let withFormat = "my name is %@ and i study in class %@"

There are different ways to do so, but in my opinion, one of the easiest way would be to use tags:

Use tags around the placeholders (and other parts if needed):

let withFormat = "my name is %@ and i study in class %@"
let withFormat = "my name is [b]%@[/b] and i study in class [b]%@[/b]"
let withFormat = "my name is **%@** and i study in class **%@**"

Tags can be HTML, Markdown, BBCode, or any custom you'd like, then, replace the placeholder values:

let localized = String(format: withFormat, value1, value2)

Now, depending on how you want to do it, or which tag you used, you can use the init of NSAttributedString from HTML, Markdown, etc, or simply using NSAttributedString(string: localized), look yourself for the tags and apply the render effect needed.

Here's a little example:

let tv = UITextView(frame: CGRect(x: 0, y: 0, width: 300, height: 130))
tv.backgroundColor = .orange

let attributedString = NSMutableAttributedString()

let htmled = String(format: "my name is %@ and i study in class %@", arguments: ["Alice", "Wonderlands"])
let markdowned = String(format: "my name is **%@** and i study in class **%@**", arguments: ["Alice", "Wonderlands"])
let bbcoded = String(format: "my name is [b]%@[/b] and i study in class [b]%@[/b]", arguments: ["Alice", "Wonderlands"])

let separator = NSAttributedString(string: "\n\n")
let html = try! NSAttributedString(data: Data(htmled.utf8), options: [.documentType : NSAttributedString.DocumentType.html], documentAttributes: nil)
attributedString.append(html)
attributedString.append(separator)

let markdown = try! NSAttributedString(markdown: markdowned, baseURL: nil) //iO15+
attributedString.append(markdown)
attributedString.append(separator)

let bbcode = NSMutableAttributedString(string: bbcoded)
let regex = try! NSRegularExpression(pattern: "\\[b\\](.*?)\\[\\/b\\]", options: [])
let matches = regex.matches(in: bbcode.string, options: [], range: NSRange(location: 0, length: bbcode.length))
let boldEffect: [NSAttributedString.Key: Any] = [.font: UIFont.boldSystemFont(ofSize: 12)]
//We use reversed() because if you replace the first one, you'll remove [b] and [/b], meaning that the other ranges will be affected, so the trick is to start from the end
matches.reversed().forEach { aMatch in
let valueRange = aMatch.range(at: 1) //We use the regex group
let replacement = NSAttributedString(string: bbcode.attributedSubstring(from: valueRange).string, attributes: boldEffect)
bbcode.replaceCharacters(in: aMatch.range, with: replacement)
}
attributedString.append(bbcode)

tv.attributedText = attributedString

Output:

Sample Image

Make part of a UILabel bold in Swift

You will want to use attributedString which allows you to style parts of a string etc. This can be done like this by having two styles, one normal, one bold, and then attaching them together:

let boldText = "Filter:"
let attrs = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15)]
let attributedString = NSMutableAttributedString(string:boldText, attributes:attrs)

let normalText = "Hi am normal"
let normalString = NSMutableAttributedString(string:normalText)

attributedString.append(normalString)

When you want to assign it to a label:

label.attributedText = attributedString

Make Ints within a string bold - swift

Quickly done, you can use a Regular Expression to find the ranges of all the numbers. Then, on these ranges, you change the attribute for a bold font.

let attributedString = NSMutableAttributedString(string: str, attributes: [.foregroundColor: UIColor.white])
let regex = try! NSRegularExpression(pattern: "\\d+", options: [])
let matches = regex.matches(in: attributedString.string, options: [], range: NSRange(location: 0, length: attributedString.length))
matches.forEach {
attributedString.addAttributes([.font: UIFont.boldSystemFont(ofSize: 17)], range: $0.range)
}

Making specific words in a title label bold in a UIButton in swift?

Use button setAttributedTitle property for set attributed text.

First, create attributed text.

Here, I created a string extension for bold attributed text. Which return attributed text and set this attributed text to button.

extension String {
/// Return attributed string
/// - Parameter text: String text for bold text.
func getAttributedBoldText(text: String) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: self, attributes: [.foregroundColor: UIColor.blue])
if let range = self.range(of: text) {
let startIndex = self.distance(from: self.startIndex, to: range.lowerBound)
let range = NSMakeRange(startIndex, text.count)
attributedString.addAttributes([.font : UIFont.boldSystemFont(ofSize: 20)], range: range)
}
return attributedString
}
}

Usage :

private let createAccountButton: UIButton = {
let button = UIButton()
button.setTitleColor(.white, for: .normal)
button.setAttributedTitle("dont have an account? sign up!".getAttributedBoldText(text: "sign up!"), for: .normal) // Here
return button
}()

Note: Modify the extension attributed function as per your layout.



Related Topics



Leave a reply



Submit