let label = UILabel() label. attributedText = NSMutableAttributedString() . bold("Address: ") .
First create an NSMutableAttributedString with a new font attribute. You don't use textView. text . Then append another attributed string that doesn't have any attributes set.
Usage:
let label = UILabel()
label.attributedText =
NSMutableAttributedString()
.bold("Address: ")
.normal(" Kathmandu, Nepal\n\n")
.orangeHighlight(" Email: ")
.blackHighlight(" [email protected] ")
.bold("\n\nCopyright: ")
.underlined(" All rights reserved. 2020.")
Result:
Here is a neat way to make a combination of bold and normal texts in a single label plus some other bonus methods.
Extension: Swift 5.*
extension NSMutableAttributedString {
var fontSize:CGFloat { return 14 }
var boldFont:UIFont { return UIFont(name: "AvenirNext-Bold", size: fontSize) ?? UIFont.boldSystemFont(ofSize: fontSize) }
var normalFont:UIFont { return UIFont(name: "AvenirNext-Regular", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize)}
func bold(_ value:String) -> NSMutableAttributedString {
let attributes:[NSAttributedString.Key : Any] = [
.font : boldFont
]
self.append(NSAttributedString(string: value, attributes:attributes))
return self
}
func normal(_ value:String) -> NSMutableAttributedString {
let attributes:[NSAttributedString.Key : Any] = [
.font : normalFont,
]
self.append(NSAttributedString(string: value, attributes:attributes))
return self
}
/* Other styling methods */
func orangeHighlight(_ value:String) -> NSMutableAttributedString {
let attributes:[NSAttributedString.Key : Any] = [
.font : normalFont,
.foregroundColor : UIColor.white,
.backgroundColor : UIColor.orange
]
self.append(NSAttributedString(string: value, attributes:attributes))
return self
}
func blackHighlight(_ value:String) -> NSMutableAttributedString {
let attributes:[NSAttributedString.Key : Any] = [
.font : normalFont,
.foregroundColor : UIColor.white,
.backgroundColor : UIColor.black
]
self.append(NSAttributedString(string: value, attributes:attributes))
return self
}
func underlined(_ value:String) -> NSMutableAttributedString {
let attributes:[NSAttributedString.Key : Any] = [
.font : normalFont,
.underlineStyle : NSUnderlineStyle.single.rawValue
]
self.append(NSAttributedString(string: value, attributes:attributes))
return self
}
}
Note: If compiler is missing UIFont/UIColor, replace them with NSFont/NSColor.
var normalText = "Hi am normal"
var boldText = "And I am BOLD!"
var attributedString = NSMutableAttributedString(string:normalText)
var attrs = [NSAttributedString.Key.font : 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
edit/update: Xcode 13.1 • Swift 5.5.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 StringProtocol {
var html2AttStr: NSAttributedString? {
try? NSAttributedString(data: Data(utf8), options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: 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
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
For Swift 4 and higher that is a good way:
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
In the Label the Text looks like: "Hi John"
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)
I extended David West's great answer so that you can input a string and tell it all the substrings you would like to embolden:
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
}
And then call it like this:
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!)
This will embolden all the substrings you want bolded in your given string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With