4
votes

Currently I am working on a project where I need to make the entire application to work with the dynamic type which means all the text in the app can be resized via the phone settings app.

All the labels have a tick in the Attributes Inspector thats called "Dynamic Type - Automatically Adjust Font" which when ticked the label can be dynamically resized.

Keep in mind that my app is in iOS 10 and all of the fonts have to be the default system font so I can apply the text styles (title 1, body, callout etc) which then allows the text to be dynamically resized.

Now the problem is that I have labels with attributed text. In my case I have a label that contains 2 different colors and the text with the second color is underlined. There is no option to get Dynamic Type with an attributed label so it cannot resize.

My temporary solution was to create 2 different labels each with its own color. But the second one HAS to be underlined. I don't know how to achieve that. I tried adding a line under it (UIView that is one pixel tall) but the line does not adjust with the dynamic text size which means when I resize the text the line stays the same.

example image

Above you can see my temporary solution. The text size does adjust with 2 different labels but the underline stays the same (the UIView that is one pixel tall).

Any suggestions on how to achieve this? Much appreciated.

1

1 Answers

0
votes

Put your "Contact" and "Us" words as one NSMutableAttributedString to add the underlineStyle attribute as follows :

    @IBOutlet weak var myLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let myString = "Contact Us"

        let myText = NSMutableAttributedString(string:myString,
                                               attributes: [
                                                .font: UIFontMetrics(forTextStyle: .title1).scaledFont(for: UIFont(name:"HoeflerText-Black", size:18)!,
                                                .underlineStyle:NSUnderlineStyle.single.rawValue)
                    ])

        myLabel.attributedText = myText
    }

Using Dynamic Type with this snippet provides the result you wished; enter image description here