Make half UILabel bold Swift 4


This time I tried to make UILabel part of a bold text,  using func so that many other UILabels can be used.





import UIKit

class MentionHalfBoldViewController: UIViewController {
    @IBOutlet weak var labelBold: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        labelBold.attributedText = attributedTextWith(withString: String(format: "Name : %@", "Jonny"), boldString: "Name", font: labelBold.font)
    }
    
    func attributedTextWith(withString string: String, boldString: String, font: UIFont) -> NSAttributedString {
        let attributedString = NSMutableAttributedString(string: string,
                                                         attributes: [NSAttributedStringKey.font: font])
        let boldFontAttribute: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: font.pointSize)]
        let range = (string as NSString).range(of: boldString)
        attributedString.addAttributes(boldFontAttribute, range: range)
        return attributedString
    }
}

No comments: