Home > front end >  Making specific words in a title label bold in a UIButton in swift?
Making specific words in a title label bold in a UIButton in swift?

Time:12-21

I'm a beginner at swift and I've found that this StackOverflow question and this StackOverflow question has not helped me with my case, most probably because I've coded it differently to them (ie Swift, not Obc).

    private let createAccountButton: UIButton = {
        let button = UIButton()
        button.setTitleColor(.white, for: .normal)
        button.setTitle("dont have an account? sign up!", for: .normal) //line 4
        return button

I would like the text "sign up!" in line 4 to be formatted in bold but haven't found anything online that can support it with the current way I've coded it.

CodePudding user response:

Use button setAttributedTitle property for set attributed text.

First, create attributed text.

Here, I created a string extension for bold attributed text. Which return attributed text and set this attributed text to button.

extension String {
    /// Return attributed string
    /// - Parameter text: String text for bold text.
    func getAttributedBoldText(text: String) -> NSMutableAttributedString {
        let attributedString = NSMutableAttributedString(string: self, attributes: [.foregroundColor: UIColor.blue])
        if let range = self.range(of: text) {
            let startIndex = self.distance(from: self.startIndex, to: range.lowerBound)
            let range = NSMakeRange(startIndex, text.count)
            attributedString.addAttributes([.font : UIFont.boldSystemFont(ofSize: 20)], range: range)
        }
        return attributedString
    }
}

Usage :

private let createAccountButton: UIButton = {
    let button = UIButton()
    button.setTitleColor(.white, for: .normal)
    button.setAttributedTitle("dont have an account? sign up!".getAttributedBoldText(text: "sign up!"), for: .normal) // Here
    return button
}()

Note: Modify the extension attributed function as per your layout.

  • Related