Make part of a UILabel bold in Swift

Nick89 picture Nick89 · Apr 7, 2016 · Viewed 42.7k times · Source

I have a UILabel I've made programmatically as:

var label = UILabel()

I've then declared some styling for the label, including a font, such as:

label.frame = CGRect(x: 20, y: myHeaderView.frame.height / 2, width: 300, height: 30)
label.font = UIFont(name: "Typo GeoSlab Regular Demo", size: 15)
label.textColor = UIColor(hue: 0/360, saturation: 0/100, brightness: 91/100, alpha: 1)

The first part of the label will always read : "Filter:" then followed by another part of the string, for example, "Most popular"

I would like the word filter to be in bold, so the whole thing would look like:

Filter: Most popular

I want to simplest way of creating this effect. I've been searching the internet for how to achieve this and there are so many ways, some which just look like pages of code. And most of it seems to be in Objective-C. I would like it in Swift please :)

I don't know if i'm on the right lines, but is this what NSRange can help achieve? Thanks in advance

Update

I use a series of if statements to change my label variable. Such as:

if indexArray == 1 {

    label.text = "Filter: Film name"

} else if indexArray == 2 {

    label.text = "Filter: Most popular"

} else if indexArray == 3 {

    label.text = "Filter: Star rating"

}

Answer

Joe Benton picture Joe Benton · Apr 7, 2016

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