Making Parts of Text Bold in Swiftui

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

How do I make a SwiftUi Button's text larger and/or bold

Use the bold() Text modifier on a Button's label.

Example:

Button {
print("Button tapped!")
} label: {
Text("Tap me").bold()
}

To make the text larger and bold, just chain the modifiers:

Button {
print("Button tapped!")
} label: {
Text("Tap me")
.font(.title)
.bold()
}

How to bold text in SwiftUI TextField?


import SwiftUI

struct ContentView: View {
@State var TextValue: String = "Hello"

var body: some View {
VStack {
TextField("placeholder", text: $TextValue)
.padding(.horizontal, 50)
.font(.system(size: 30, weight: .heavy, design: .default))
}
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

Sample Image

Is it possible to make SwiftUI List item text selectively bold for FAQ section?

You could check if a row has any children to decide whether to bold the text or not.

List(questionItems, children: \.textTwo) { item in
if item.hasChildren {
Text(item.textOne)
.bold()
.padding([.top, .bottom], 15)
} else {
Text(item.textOne)
.padding([.top, .bottom], 15)
}
}

extension QuestionAnswer {
var hasChildren: Bool { !(textTwo?.isEmpty == true) }
}

Or with suggested approach from the comments

List(questionItems, children: \.textTwo) { item in
Text(item.hasChildren ? "**\(item.textOne)**" : item.textOne )
.padding([.top, .bottom], 15)
}

How to use bold and normal text in same line in SwiftUI

Here a simple example for you, with my example code you can code for iOS 13 or 14 as well:

struct ContentView: View {

var body: some View {

Text("Hello, World!") + Text(" Hello, World!").bold() + Text(" Hello, World!").italic()

}

}

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

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 <b>%@</b> and i study in class <b>%@</b>"
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 <b>%@</b> and i study in class <b>%@</b>", 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



Related Topics



Leave a reply



Submit