1

I've tried a couple of different methods and extensions after coming across them on S.O. to no avail. Is there a definitive way to bold only part of a UIButton.titleLabel?

These are some of the extensions I've tried:

func attributedText(fullStr: String, boldStr: String) -> NSAttributedString {

                let attributedString = NSMutableAttributedString(string: fullStr as String, attributes: [NSFontAttributeName:UIFont.systemFontOfSize(12.0)])

                let boldFontAttribute = [NSFontAttributeName: UIFont.boldSystemFontOfSize(12.0)]

                // Part of string to be bold
                attributedString.addAttributes(boldFontAttribute, range: NSMakeRange(0, boldStr.characters.count))


               return attributedString
}


func boldRange(range: Range<String.Index>) {
                if let text = self.attributedTitleForState(UIControlState.Normal) {
                    let attr = NSMutableAttributedString(attributedString: text)
                    let start = text.string.startIndex.distanceTo(range.startIndex)
                    let length = range.startIndex.distanceTo(range.endIndex)
                    attr.addAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(16)], range: NSMakeRange(start, length))
                    self.setAttributedTitle(attr, forState: UIControlState.Normal)
                }
}


func boldSubstring(substr: String) {
                let range = substr.rangeOfString(substr)
                if let r = range {
                    boldRange(r)
                }
}

Anyone have anything?

slider
  • 2,736
  • 4
  • 33
  • 69
  • it's not clear where ur code entry point is nor whether your `NSAttributedString` object is properly set on the `UIButton`. Here is an example on SO for how to use it. It's Obj-C but you should be able to understand it still: http://stackoverflow.com/questions/17756067/ios-nsattributedstring-on-uibutton – JackyJohnson Jan 23 '16 at 03:21
  • Found working answer in this other [post](https://stackoverflow.com/questions/25207373/changing-specific-texts-color-using-nsmutableattributedstring-in-swift/40016586). –  May 17 '19 at 19:04

1 Answers1

1

Swift 4 version of chicobermuda's answer:

let text = "This is the"
let attr = NSMutableAttributedString(string: "\(text) button's text!")
attr.addAttribute(NSAttributedStringKey.font, value: UIFont.boldSystemFont(ofSize: 14), range: NSMakeRange(0, text.count))
cell.nameLabel.setAttributedTitle(attr, forState: .normal)

// "**This is the** button's text!"

it works fine

Max
  • 636
  • 3
  • 13
  • 28