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
Swift make UILabel text bold in between custom identifier
First, get the strings within the delimiter.
let query = "This is not bold, -bold- this is bold, -/bold- and this is another not bold, -bold- this is another bold -/bold-"
let regex = try! NSRegularExpression(pattern: "-bold- (.*?) -/bold-", options: [])
var results = [String]()
regex.enumerateMatches(in: query, options: [], range: NSMakeRange(0, query.utf16.count)) { result, flags, stop in
if let r = result?.range(at: 1),
let range = Range(r, in: query) {
results.append(String(query[range]))
}
}
print(results)
Next, Create a string extension method like below.
extension String {
func attributedString(with style: [NSAttributedString.Key: Any]? = nil,
and highlightedTextArray: [String],
with highlightedTextStyleArray: [[NSAttributedString.Key: Any]?]) -> NSAttributedString {
let formattedString = NSMutableAttributedString(string: self, attributes: style)
if highlightedTextArray.count != highlightedTextStyleArray.count {
return formattedString
}
for (highlightedText, highlightedTextStyle) in zip(highlightedTextArray, highlightedTextStyleArray) {
let highlightedTextRange: NSRange = (self as NSString).range(of: highlightedText as String)
formattedString.setAttributes(highlightedTextStyle, range: highlightedTextRange)
}
return formattedString
}
}
Method details:
- first argument: Font style and other attributes to be applied for
complete string. - second argument: Array of strings for which new style to be applied.
- third argument: New Style (in this case, Bold) to be applied.
- returns resultant attributed string.
Finally, call the method as below.
let attributedText = query.attributedString(with: [.font: UIFont.systemFont(ofSize: 12.0, weight: .regular)],
and: results,
with: [[.font: UIFont.systemFont(ofSize: 12.0, weight: .bold)]])
Hope it helps.
How to make part of a string bold in iOS?
Yes, it can be achieved with NSAttributedString
:
NSString *yourString = @"This is to be bold. This is normal string.";
NSMutableAttributedString *yourAttributedString = [[NSMutableAttributedString alloc] initWithString:yourString];
NSString *boldString = @"This is to be bold";
NSRange boldRange = [yourString rangeOfString:boldString];
[yourAttributedString addAttribute: NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:boldRange];
[yourLabel setAttributedText: yourAttributedString];
Swift: Programmatically make UILabel bold without changing its size?
Why not just:
titleLabel.font = UIFont.boldSystemFont(ofSize: titleLabel.font.pointSize)
Partially Bold Text in UILabel
If you just want the names to appear in bold, use the UILabel
attributedText
attribute to set an attributed string instead of a plain text string.
Something like:
let name = names[indexPath.row]
let color = colors[indexPath.row]
let attributedText = NSMutableAttributedString(string: name, attributes:[NSFontAttributeName : UIFont.boldSystemFont(ofSize:15)])
attributedText.append(NSAttributedString(string:color))
cell.info.attributedText = attributedText
Of course, you'd need to set the font in the above for the bold part according to how you have the cell styled.
Set part of a UILabel's text bold and another part italic
You can do this by using NSMutableAttributedString
NSMutableAttributedString *strText = [[NSMutableAttributedString alloc] initWithString:@"Setting different for label text"];
[strText addAttribute:NSFontAttributeName
value:[UIFont fontWithName:@"Helvetica-Bold" size:22]
range:NSMakeRange(0, 10)];
[strText addAttribute:NSFontAttributeName
value:[UIFont fontWithName:@"Helvetica-Italic" size:22]
range:NSMakeRange(10, 10)];
Swift 4 code:
var strText = NSMutableAttributedString(string: "Setting different for label text")
strText.addAttribute(.font, value: UIFont(name: "Helvetica-Bold", size: 22)!, range: NSRange(location: 0, length: 10))
strText.addAttribute(.font, value: UIFont(name: "Helvetica-Italic", size: 22)!, range: NSRange(location: 10, length: 10))
Making parts of text bold in SwiftUI
iOS 15+ (Swift 5.5 +)
SwiftUI has built-in support for rendering Markdown.
It is GitHub flavored markdown. AttributedString converts both inline and block styles. SwiftUI renders inline styles (but not images at this time). We use the fantastic cmark-gfm library to parse the markdown string. - SwiftUI Frameworks Engineer - developer.apple.com
See more:
What is Markdown?
Use double asterisks (**) arroud the characters that you want to make bold.
Text("**CO**rona**V**irus **D**isease of 20**19**")
Use underscore (_) arround the charachters you want to make italic.
Text("Is this text _emphasized_?")
String variable
Use init(_ value: String)
Creates a localized string key from the given string value.
let bold = "This text is **bold**"
Text(.init(bold))
String interpolation
Use init(_ value: String)
Creates a localized string key from the given string value.
let bold = "Bold"
Text(.init("This text is **\(bold)**"))
Attributed text
Use init(_ attributedContent: AttributedString)
Creates a text view that displays styled attributed content.
let markdownText = try! AttributedString(markdown: "This text is **bold**")
Text(markdownText)
See also:
init(_ attributedContent: AttributedString)
- https://developer.apple.com
Related Topics
Swift Force-Unwrapping Exception Not Propagated
How to Disable the Back Navigation Menu in iOS 14+
Replace Occurrences of Nsnull in Nested Nsdictionary
Will iOS Region Monitoring Call Didenterregion on My App If My App Is in a Terminated State
Aes/Cbc/Pkcs5Padding in iOS Objective C Result Differs from Android
Xcode 6 Gm - Cllocationmanager
How to Use Call Directory Extension to Identify a Incoming Call in My Application
Sbstatusbarcontroller Instance
iOS 6.X Open Command Line on Jailbreak
Can't Cast Value of Type Uiviewcontroller to Patterndetailviewcontroller
iOS - Push Viewcontroller from Code and Storyboard
How to Draw a Single Point Line in iOS
Wrap Items in a Horizontal Uistackview on Multiple Lines
Xcode Version 6.1 (6A1030) - Apple MACh O-Linker Error - Building
How to Keep Uiswitch State When Changing Viewcontrollers
Searchdisplaycontroller Deprecated in iOS 8
Get the Frame of Uibarbuttonitem in Swift
Cordova Run with iOS Error .. Error Code 65 for Command: Xcodebuild with Args: