Search code examples
swiftswift3uilabel

Force UILabel to take up 3 lines


I am working on a music player and have labels set up for the song, album, and artist. Now, just for the sake of UI, I would like the song label to always use space for 3 lines, even if the text is 1 line. I have set the number of lines to 3 in the attributes inspector, but it only shows 3 lines if the song title is actually that long!

My first idea of a workaround is to lock the height of the label to 3X the text size(and then some for spacing). Is there maybe a better solution? Or a different object I could use?


Solution

  • To force a UILabel to take up three lines as in a music player, you'll just need to add line breaks at the appropriate places with \n and set the label's lines to 3.

    Adding line breaks:

    var title = "Title"
    var album = "Album"
    var artist = "Artist"
    
    label.text = "\(title)\n" +
          "\(album)\n" +
          "\(artist)\n"
    

    Setting label to 3 lines:

    label.numberOfLines = 3 // or set this to 4 or higher if the title of the song might exceed one line