Skip to content

Instantly share code, notes, and snippets.

@backslash-f
Created July 4, 2018 09:37
Show Gist options
  • Save backslash-f/e9e8e6b21ab7914325c57b66d9a9ab85 to your computer and use it in GitHub Desktop.
Save backslash-f/e9e8e6b21ab7914325c57b66d9a9ab85 to your computer and use it in GitHub Desktop.
Make the first line of a UILabel (any multi line text really) bold
import UIKit
import PlaygroundSupport
extension UILabel {
/// Makes the first line (of a multiline label) bold.
/// In case the label is a "single line" one, the function does nothing.
/// In case there is no bold version of the current font, the function does nothing.
public func makeFirstLineBold() {
// Current text.
guard let text = text else { return }
// First line.
let components = text.components(separatedBy: .newlines)
guard components.count > 1, let firstLine = components.first else { return }
// Bold version of the current font.
guard let boldFont = font.bold() else { return }
// Attributed bold.
let boldFontAttribute: [NSAttributedStringKey: Any] = [.font: boldFont]
let boldRange = (text as NSString).range(of: firstLine)
// Attributed text.
let attributedText = NSMutableAttributedString(string: text, attributes: [.font: font])
attributedText.addAttributes(boldFontAttribute, range: boldRange)
// Updated label's attributed text.
self.attributedText = attributedText
}
}
extension UIFont {
/// Returns the bold version of the `self`. Or `nil` if it could not be found.
func bold() -> UIFont? {
let fontDescriptorSymbolicTraits: UIFontDescriptorSymbolicTraits = [fontDescriptor.symbolicTraits, .traitBold]
let bondFontDescriptor = fontDescriptor.withSymbolicTraits(fontDescriptorSymbolicTraits)
return bondFontDescriptor.flatMap { UIFont(descriptor: $0, size: pointSize) }
}
}
class LabelViewController : UIViewController {
override func loadView() {
let text = """
You’ll get your last delivery on Mon, Mar 26
Thanks for trying us out! We'd love to hear what you think about your experience.
"""
let view = UIView()
view.backgroundColor = .white
let label = UILabel()
label.text = text
label.textAlignment = .center
label.numberOfLines = 0
label.makeFirstLineBold()
view.addSubview(label)
// Layout
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.topAnchor.constraint(equalTo: view.topAnchor, constant: 0),
label.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0),
label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0),
label.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0)
])
self.view = view
}
}
PlaygroundPage.current.liveView = LabelViewController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment