Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add padding to a NSMutableAttributedString?

I have a label that uses a NSMutableAttributedString to write out the text as:

enter image description here

What I want to do is lower the asterisk's top padding so that it's midY is even with the word Cuisine like below:

enter image description here

How can I add padding using a NSMutableAttributedString?

I know I can create a separate label with the asterisk alone and use anchors w/ a constant to center it but I want to see how this is possible using a NSMutableAttributedString

let cuisineLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false

    let attributedText = NSMutableAttributedString(string: "Cuisine ", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17), NSAttributedStringKey.foregroundColor: UIColor.lightGray])

    attributedText.append(NSAttributedString(string: "*", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 24), NSAttributedStringKey.foregroundColor: UIColor.red]))

    label.attributedText = attributedText

    return label
}()
like image 447
Lance Samaria Avatar asked Sep 14 '18 16:09

Lance Samaria


1 Answers

The baselineOffset attribute key is used for this purpose.

let cuisine = NSMutableAttributedString(string: "Cuisine")
let asterisk = NSAttributedString(string: "*", attributes: [.baselineOffset: -3])
cuisine.append(asterisk)

enter image description here

Obviously, you will have to calculate the offset using the font size of the rest of the text. This is why I believe that using a full width asterisk (*) is easier.

Result with full width asterisk (you might want its font size to be a proportion of the font size of the rest of the string):

enter image description here

like image 121
Sweeper Avatar answered Sep 22 '22 14:09

Sweeper